public void Test_Sftp_CreateDirectory_In_Forbidden_Directory()
        {
            if (Resources.USERNAME == "root")
                Assert.Fail("Must not run this test as root!");

            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.CreateDirectory("/sbin/test");

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_Rename_File()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string remoteFileName1 = Path.GetRandomFileName();
                string remoteFileName2 = Path.GetRandomFileName();

                this.CreateTestFile(uploadedFileName, 1);

                using (var file = File.OpenRead(uploadedFileName))
                {
                    sftp.UploadFile(file, remoteFileName1);
                }

                sftp.RenameFile(remoteFileName1, remoteFileName2);

                File.Delete(uploadedFileName);

                sftp.Disconnect();
            }

            RemoveAllFiles();
        }
        public void Test_Sftp_SynchronizeDirectories()
        {
            RemoveAllFiles();

            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string uploadedFileName = Path.GetTempFileName();

                string sourceDir = Path.GetDirectoryName(uploadedFileName);
                string destDir = "/";
                string searchPattern = Path.GetFileName(uploadedFileName);
                var upLoadedFiles = sftp.SynchronizeDirectories(sourceDir, destDir, searchPattern);

                Assert.IsTrue(upLoadedFiles.Count() > 0);

                foreach (var file in upLoadedFiles)
                {
                    Debug.WriteLine(file.FullName);
                }

                sftp.Disconnect();
            }
        }
        protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Loose);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _operationTimeout = TimeSpan.FromSeconds(new Random().Next(1, 10));
            _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _sftpClient.OperationTimeout = _operationTimeout;

            _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.Setup(p => p.Connect());
            _serviceFactoryMock.Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding))
                .Returns(_sftpSessionMock.Object);
            _sftpSessionMock.Setup(p => p.Connect());

            _sftpClient.Connect();
            _sftpClient = null;

            _serviceFactoryMock.Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding))
                .Returns((ISftpSession)  null);
            _serviceFactoryMock.ResetCalls();

            // we need to dereference all other mocks as they might otherwise hold the target alive
            _sessionMock = null;
            _connectionInfo = null;
            _serviceFactoryMock = null;
        }
        protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _operationTimeout = TimeSpan.FromSeconds(new Random().Next(1, 10));
            _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _sftpClient.OperationTimeout = _operationTimeout;

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding))
                .Returns(_sftpSessionMock.Object);
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect());
            _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Disconnect());
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _sessionMock.InSequence(sequence).Setup(p => p.Disconnect());
            _sessionMock.InSequence(sequence).Setup(p => p.Dispose());

            _sftpClient.Connect();
            _sftpClient.Disconnect();
        }
        public void Test_Sftp_SftpFile_MoveTo()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string remoteFileName = Path.GetRandomFileName();
                string newFileName = Path.GetRandomFileName();

                this.CreateTestFile(uploadedFileName, 1);

                using (var file = File.OpenRead(uploadedFileName))
                {
                    sftp.UploadFile(file, remoteFileName);
                }

                var sftpFile = sftp.Get(remoteFileName);

                sftpFile.MoveTo(newFileName);

                Assert.AreEqual(newFileName, sftpFile.Name);

                sftp.Disconnect();
            }
        }
        public void Test_KeyboardInteractiveConnectionInfo()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example KeyboardInteractiveConnectionInfo AuthenticationPrompt
            var connectionInfo = new KeyboardInteractiveConnectionInfo(host, username);
            connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
            {
                System.Console.WriteLine(e.Instruction);

                foreach (var prompt in e.Prompts)
                {
                    Console.WriteLine(prompt.Request);
                    prompt.Response = Console.ReadLine();
                }
            };

            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion

            Assert.AreEqual(connectionInfo.Host, Resources.HOST);
            Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
        }
 public void Test_Sftp_ChangeDirectory_Root_Dont_Exists()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         sftp.ChangeDirectory("/asdasd");
     }
 }
 public void Test_Sftp_ChangeDirectory_Subfolder_With_Slash_Dont_Exists()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         sftp.ChangeDirectory("/asdasd/sssddds/");
     }
 }
示例#10
0
        public void Test_Get_Invalid_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.Get("/xyz");
            }
        }
示例#11
0
 public void Test_Sftp_BeginUploadFile_FileNameIsWhiteSpace()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         sftp.BeginUploadFile(new MemoryStream(), "   ", null, null);
         sftp.Disconnect();
     }
 }
示例#12
0
 public void Test_Sftp_BeginUploadFile_StreamIsNull()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         sftp.BeginUploadFile(null, "aaaaa", null, null);
         sftp.Disconnect();
     }
 }
 public void Test_Sftp_ChangeDirectory_Which_Exists()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         sftp.ChangeDirectory("/usr");
         Assert.AreEqual("/usr", sftp.WorkingDirectory);
     }
 }
 public void Test_Sftp_Call_EndListDirectory_Twice()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         var ar = sftp.BeginListDirectory("/", null, null);
         var result = sftp.EndListDirectory(ar);
         var result1 = sftp.EndListDirectory(ar);
     }
 }
        public void Test_Sftp_DeleteDirectory_Which_Doesnt_Exists()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.DeleteDirectory("abcdef");

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_CreateDirectory_In_Current_Location()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.CreateDirectory("test");

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_CreateDirectory_Invalid_Path()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.CreateDirectory("/abcdefg/abcefg");

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_RenameFile_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.RenameFile(null, null);

                sftp.Disconnect();
            }
        }
示例#19
0
        public void Test_Get_File_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                var file = sftp.Get(null);

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_ChangeDirectory_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.ChangeDirectory(null);

                sftp.Disconnect();
            }
        }
示例#21
0
        public void Test_Get_Root_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();
                var directory = sftp.Get("/");

                Assert.AreEqual("/", directory.FullName);
                Assert.IsTrue(directory.IsDirectory);
                Assert.IsFalse(directory.IsRegularFile);
            }
        }
示例#22
0
 public void Test_Sftp_EndUploadFile_Invalid_Async_Handle()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         var async1 = sftp.BeginListDirectory("/", null, null);
         var filename = Path.GetTempFileName();
         this.CreateTestFile(filename, 100);
         var async2 = sftp.BeginUploadFile(File.OpenRead(filename), "test", null, null);
         sftp.EndUploadFile(async1);
     }
 }
        public void Test_Sftp_CreateDirectory_Already_Exists()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.CreateDirectory("test");

                sftp.CreateDirectory("test");

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_DeleteDirectory_Which_No_Permissions()
        {
            if (Resources.USERNAME == "root")
                Assert.Fail("Must not run this test as root!");

            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.DeleteDirectory("/usr");

                sftp.Disconnect();
            }
        }
示例#25
0
        public void Test_Get_File()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.UploadFile(new MemoryStream(), "abc.txt");

                var file = sftp.Get("abc.txt");

                Assert.AreEqual("/home/tester/abc.txt", file.FullName);
                Assert.IsTrue(file.IsRegularFile);
                Assert.IsFalse(file.IsDirectory);
            }
        }
        public void Test_Sftp_Download_File_Not_Exists()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string remoteFileName = "/xxx/eee/yyy";
                using (var ms = new MemoryStream())
                {
                    sftp.DownloadFile(remoteFileName, ms);
                }

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_ListDirectory_Not_Exists()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                var files = sftp.ListDirectory("/asdfgh");
                foreach (var file in files)
                {
                    Debug.WriteLine(file.FullName);
                }

                sftp.Disconnect();
            }
        }
示例#28
0
        public void Connect_HostNameInvalid_ShouldThrowSocketExceptionWithErrorCodeHostNotFound()
        {
            var connectionInfo = new ConnectionInfo("invalid.", 40, "user",
                new KeyboardInteractiveAuthenticationMethod("user"));
            var sftpClient = new SftpClient(connectionInfo);

            try
            {
                sftpClient.Connect();
                Assert.Fail();
            }
            catch (SocketException ex)
            {
                Assert.AreEqual(ex.ErrorCode, (int) SocketError.HostNotFound);
            }
        }
    public SftpFileStream GetRemoteFile(string filename)
    {
        // Server credentials
        var host     = "host";
        var port     = 22;
        var username = "******";
        var password = "******";

        sftp = new SftpClient(host, port, username, password);

        // Connect to the SFTP server
        sftp.Connect();

        // Read the file in question
        file = sftp.OpenRead(filename);

        return(file);
    }
        public void Test_Sftp_ListDirectory_Current()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                var files = sftp.ListDirectory(".");

                Assert.IsTrue(files.Count() > 0);

                foreach (var file in files)
                {
                    Debug.WriteLine(file.FullName);
                }

                sftp.Disconnect();
            }
        }
示例#31
0
 public IEnumerable <SftpFile> ListAllFiles(string remoteDirectory = ".")
 {
     using var client = new SftpClient(_host, _port == 0 ? 22 : _port, _username, _password);
     try
     {
         client.Connect();
         return(client.ListDirectory(remoteDirectory));
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception);
         return(Enumerable.Empty <SftpFile>());
     }
     finally
     {
         client.Disconnect();
     }
 }
示例#32
0
        public clsSFTP(dbData3060DataContext p_dbData3060)
        {
#if (DEBUG)
            m_rec_sftp = (from s in p_dbData3060.tblsftps where s.navn == "TestHD36" select s).First();
            //m_rec_sftp = (from s in p_dbData3060.tblsftps where s.navn == "Test" select s).First();
            //m_rec_sftp = (from s in p_dbData3060.tblsftps where s.navn == "Produktion" select s).First();
#else
            //m_rec_sftp = (from s in p_dbData3060.tblsftps where s.navn == "Test" select s).First();
            m_rec_sftp = (from s in p_dbData3060.tblsftps where s.navn == "Produktion" select s).First();
#endif
            Program.Log(string.Format("host={0}, port={1}, user={2}", m_rec_sftp.host, int.Parse(m_rec_sftp.port), m_rec_sftp.user), "SFTP ConnectionString");
            byte[]         bPK = Encoding.UTF8.GetBytes(m_rec_sftp.certificate);
            MemoryStream   mPK = new MemoryStream(bPK);
            PrivateKeyFile PK  = new PrivateKeyFile(mPK, m_rec_sftp.pincode);
            m_sftp = new SftpClient(m_rec_sftp.host, int.Parse(m_rec_sftp.port), m_rec_sftp.user, PK);
            m_sftp.Connect();
            Program.Log("SFTP Connected");
        }
        // Does the actual job
        public void Watch(string folderFullPath)
        {
            bool isFirstRun = this.files == null;

            if (isFirstRun)
            {
                this.files = new Dictionary <string, DateTime>();
            }

            this.error = string.Empty;
            try
            {
                // Intentionally NOT passing any creds via parameters or entity state. Don't want them to be stored anywhere.
                this.GetParams(folderFullPath, out var serverName, out var folderName, out var fileMask, out var userName, out var password);

                string timeoutString = Environment.GetEnvironmentVariable("SFTP_TIMEOUT_IN_SECONDS");
                var    timeout       = TimeSpan.FromSeconds(string.IsNullOrEmpty(timeoutString) ? 5 : int.Parse(timeoutString));

                using (var client = new SftpClient(serverName, userName, password))
                {
                    // Not sure which one to set, so setting both
                    client.ConnectionInfo.Timeout = timeout;
                    client.OperationTimeout       = timeout;

                    client.Connect();

                    var maskRegex = new Regex(Regex.Escape(fileMask).Replace("\\*", ".+"));
                    var newFiles  = ListFilesInFolder(client, folderName, maskRegex);

                    // Emitting events
                    if (!isFirstRun || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("STAY_SILENT_AT_FIRST_RUN")))
                    {
                        this.EmitEvents(serverName, this.files, newFiles);
                    }

                    // Updating our state
                    this.files = newFiles;
                }
            }
            catch (Exception ex)
            {
                this.error = ex.Message;
            }
        }
示例#34
0
        public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                foreach (var item in _options.ConfiguredHosts.Values)
                {
                    var connectionInfo = new ConnectionInfo(item.Host, item.Port, item.UserName, item.AuthenticationMethods.ToArray());

                    if (context.Registration.Timeout > TimeSpan.Zero)
                    {
                        connectionInfo.Timeout = context.Registration.Timeout;
                    }

                    using (var sftpClient = new SftpClient(connectionInfo))
                    {
                        sftpClient.Connect();

                        var connectionSuccess = sftpClient.IsConnected && sftpClient.ConnectionInfo.IsAuthenticated;
                        if (connectionSuccess)
                        {
                            if (item.FileCreationOptions.createFile)
                            {
                                using (var stream = new MemoryStream(new byte[] { 0x0 }, 0, 1))
                                {
                                    sftpClient.UploadFile(stream, item.FileCreationOptions.remoteFilePath);
                                }
                            }
                        }
                        else
                        {
                            return(Task.FromResult(
                                       new HealthCheckResult(context.Registration.FailureStatus, description: $"Connection with sftp host {item.Host}:{item.Port} failed.")));
                        }
                    }
                }

                return(HealthCheckResultTask.Healthy);
            }
            catch (Exception ex)
            {
                return(Task.FromResult(
                           new HealthCheckResult(context.Registration.FailureStatus, exception: ex)));
            }
        }
        private void Clone_Click(object sender, RoutedEventArgs e)
        {
            string selectedRepositoryName = Product_combobox.SelectedItem.ToString();

            //Clone specified tag version to the temp folder in preperation for copying to the Evo unit
            RunGitCommand("clone", "--branch " + Tags_combobox.SelectedItem + " " + appSettings.Get(selectedRepositoryName), Directory.GetCurrentDirectory() + "\\Temp"); // get all tags


            //Get selected IP from drop down menu
            for (int i = 0; i < dictPi.Count; i++)
            {
                if (dictPi.Values.ElementAt(i) == Devices_combobox.SelectedItem.ToString())
                {
                    deviceIP = dictPi.Keys.ElementAt(i).ToString();
                }
            }

            //Setup sftp connection outside of recursive copy be sure to close this connection after remote copy is finished
            SftpClient sftpClient = new SftpClient(deviceIP, "pi", "1X393c4db2");

            sftpClient.Connect();

            //Check if folder already exists on linux system. Would be nice to report the version number found in the future.
            if (sftpClient.Exists("/home/pi/PFC/" + selectedRepositoryName))
            {
                var msgBoxresult = MessageBox.Show("Target system already contains the selected software.\n\nWould you like to overwrite?", "Repository Already Present", MessageBoxButton.YesNo, MessageBoxImage.Warning);

                if (msgBoxresult == MessageBoxResult.Yes)
                {
                    LinuxRemoteCopy(sftpClient, deviceIP, "pi", "1X393c4db2", Directory.GetCurrentDirectory() + "\\Temp\\" + selectedRepositoryName, "/home/pi/PFC/" + selectedRepositoryName, true, true);
                }
            }
            else
            {
                //Folder doesn't exist just copy
                LinuxRemoteCopy(sftpClient, deviceIP, "pi", "1X393c4db2", Directory.GetCurrentDirectory() + "\\Temp\\" + selectedRepositoryName, "/home/pi/PFC/" + selectedRepositoryName, true, false);
            }

            //Disconnect ftp client
            sftpClient.Disconnect();

            //Delete Temp Folder Contents
            DeleteFolderContents(new DirectoryInfo(Directory.GetCurrentDirectory() + "\\Temp"));
        }
示例#36
0
        private void StartTaskButton_Click(object sender, RoutedEventArgs e)
        {
            if (PrnListBox.SelectedIndex != -1)
            {
                List <string> files = (from object file in PrnListBox.SelectedItems select file.ToString()).ToList();

                var amir = new Amir(files);
                amir.ExportToFile("");

                var keyFile  = new PrivateKeyFile(Config.Config.Instace.UserKeyFilePath, Cryptor.Decrypt(Config.Config.Instace.UserFingerprint, "abc123")); //todo надо сделать подобный ssh sftp-manager
                var username = Config.Config.Instace.UserLogin;

                using (var sftpclient = new SftpClient(Config.Config.Instace.ClusterHost, Config.Config.Instace.ClusterPort, username, keyFile))
                {
                    sftpclient.Connect();
                    sftpclient.ChangeDirectory(sftpclient.WorkingDirectory + "/_scratch/" + Config.Config.Instace.ClusterWorkingDirectory + TasksListBox.SelectedItem);
                    using (var fileStream = new FileStream("amir.t3c", FileMode.Open))
                    {
                        sftpclient.BufferSize = 4 * 1024; // bypass Payload error large files
                        sftpclient.UploadFile(fileStream, System.IO.Path.GetFileName("amir.t3c"), true);
                    }
                    sftpclient.Disconnect();
                }
            }

            var cmds = new List <string> {
                "module add slurm", "module load intel/13.1.0", "module load mkl/4.0.2.146", "module load openmpi/1.5.5-icc", "cd _scratch", "cd " + Config.Config.Instace.ClusterWorkingDirectory
            };

            var part = (TestRb.IsChecked == true) ? "test" : "gputest";

            foreach (var curFolder in TasksListBox.SelectedItems)
            {
                cmds.Add(String.Format("cd {0}", curFolder));
                cmds.Add(String.Format("sbatch -p {0} run i2jslab", part));
                cmds.Add("cd ..");
            }

            cmds.RemoveAt(cmds.Count - 1);

            var result = ((App)Application.Current).SSHManager.RunCommands(cmds);

            MessageBox.Show(result);
        }
示例#37
0
        private void dlConfigContextBtn_Click(object sender, EventArgs e)
        {
            if (vpnSettingsList.SelectedItems.Count > 0)
            {
                String text = vpnSettingsList.SelectedItems[0].Text;
                using (var sftp = new SftpClient(activeConnection.host, activeConnection.port, activeConnection.user, activeConnection.pass))
                {
                    sftp.Connect();

                    Stream         file     = null;
                    SaveFileDialog fileDiag = new SaveFileDialog();
                    fileDiag.Filter   = "WireGuard config|*.conf|OpenVPN config|*.ovpn";
                    fileDiag.FileName = $"{text}.conf";

                    try
                    {
                        DialogResult result = fileDiag.ShowDialog();
                        if (result == DialogResult.OK)
                        {
                            file = File.OpenWrite(fileDiag.FileName);
                            sftp.DownloadFile($"/home/{activeConnection.user}/configs/{text}.conf", file);
                            MessageBox.Show($"Config file saved.\nNow import it into WireGuard/OpenVPN depending on what your PiVPN was setup to run.", "Saved config!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            file.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Failed to download config file.\nError: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        if (file != null)
                        {
                            file.Close();
                        }

                        if (File.Exists(fileDiag.FileName) && string.IsNullOrEmpty(File.ReadAllText(fileDiag.FileName)))
                        {
                            File.Delete(fileDiag.FileName);
                        }
                    }

                    sftp.Disconnect();
                }
            }
        }
示例#38
0
        static void Main(string[] args)
        {
            //Parameters of the work to be done
            const string host              = @"";
            const int    port              = 0;
            const string username          = "";
            const string password          = @"";
            const string fileLocation      = "";
            const string keyword1          = "";
            const string keyword2          = "";
            const string newFileNamePrefix = @"";
            const string fileExt           = @"";

            //Establish connection and initialize client to perform work
            ConnectionInfo connInfo = new ConnectionInfo(host, port, username, new PasswordAuthenticationMethod(username, password));

            using SftpClient client = new SftpClient(connInfo);
            client.Connect();

            //Identify files that need to be changed
            List <SftpFile> files = client
                                    .ListDirectory($"{client.WorkingDirectory}/{fileLocation}/")
                                    .Where(file => file.Name.ToLower().Contains(keyword1) && file.Name.ToLower().Contains(keyword2))
                                    .ToList();

            files.ForEach(file =>
            {
                //Isolate pertinent value in current file name
                string isolatedValue = file.Name.Split(keyword2)[1].Split("_")[0];
                //Apply pertinent value to new file name convention
                string newName = $"{newFileNamePrefix}{isolatedValue}.{fileExt}";
                //Generate full file path for new file name
                string path    = Path.GetDirectoryName(file.FullName);
                string newFile = $"{path}\\{newName}".Replace("\\", "/");

                //Use this WriteLine to verify the original file name has been correctly transformed to the new file name
                //Console.WriteLine(file.FullName + "\n\n" + newFile);

                //Use Console.WriteLine to verify the changes that are about to be made en masse
                client.RenameFile(file.FullName, newFile);
            });

            client.Disconnect();
        }
        public static List <TreeViewModel> LoadSFTPFolders(string host, int port, string username, string password)
        {
            List <TreeViewModel> finalObjList = new List <TreeViewModel>();

            using (SftpClient sftp = new SftpClient(host, port, username, password))
            {
                try
                {
                    sftp.Connect();
                    var files        = sftp.ListDirectory("/");
                    var filteredList = files.Where(item => item.IsDirectory).ToList();
                    foreach (Renci.SshNet.Sftp.SftpFile folder in filteredList)
                    {
                        TreeViewModel obj = new TreeViewModel();
                        //push folder into final list
                        obj.Value    = folder.Name;
                        obj.Children = GetDirectorties(sftp, folder.FullName);
                        finalObjList.Add(obj);
                    }
                    sftp.Disconnect();
                }
                catch (SshConnectionException connExp)
                {
                    //throw connExp;
                    return(null);
                }
                catch (SshAuthenticationException authExp)
                {
                    //throw authExp;
                    return(null);
                }
                catch (System.Net.Sockets.SocketException socketExp) //When host is wrong or not accissible
                {
                    //throw socketExp;
                    return(null);
                }
                catch (Exception e)
                {
                    //throw e;
                    return(null);
                }
            }
            return(finalObjList);
        }
        public AKNDocOutput GetIFDoc(string opstina, string katastarskaOpstina, string brImotenList, string brParcela, bool showEMB)
        {
            try
            {
                var output = new AKNDocOutput();

                var client = new AKNDocsServiceProduction.IntegracijaWSImplClient();
                var info   = client.getPlistInfo(opstina, katastarskaOpstina, brImotenList, brParcela, "0");

                if (info == null || !string.IsNullOrEmpty(info.errmsg) || info.idPtype != "2005")
                {
                    output.HasDocument = false;
                    output.Message     = "Не постои предбележување на градба за дадените параметри!";
                    output.Document    = null;
                    return(output);
                }

                string show    = showEMB ? "1" : "0";
                var    docInfo = client.generateDocument(opstina, katastarskaOpstina, brImotenList, brParcela, show, "2005");//1014 kopija od katastarski plan
                if (docInfo.errmsg == null)
                {
                    using (var sftp = new SftpClient(Host, Port, Username, Password))
                    {
                        sftp.Connect();
                        byte[] arr = sftp.ReadAllBytes(docInfo.filePath + "//" + docInfo.fileName);
                        output.Document    = arr;
                        output.HasDocument = true;
                        output.Message     = "Успешна операција!";
                        sftp.Disconnect();
                    }
                }
                else
                {
                    output.Document    = null;
                    output.HasDocument = false;
                    output.Message     = "Настаната е грешка при креирање на документот. Обидете се повторно!";
                }
                return(output);
            }
            catch (Exception exception)
            {
                throw new Exception("Сервисот кој го повикавте врати грешка: " + exception.Message);
            }
        }
示例#41
0
        public void CreateDirectory(IntegracaoInfos sftpInfo)
        {
            int Port = 22;


            SftpClient tmpClient;

            if (!string.IsNullOrEmpty(sftpInfo.Senha))
            {
                tmpClient = new SftpClient(sftpInfo.HostURI, Port, sftpInfo.Usuario, sftpInfo.Senha);
            }
            else
            {
                var sftpModelShared = new SftpModel(sftpInfo.DiretorioInspecaoLocal, sftpInfo.HostURI,
                                                    sftpInfo.Usuario,
                                                    sftpInfo.PrivateKey, sftpInfo.Senha);
                tmpClient = new SftpClient(sftpModelShared.HostURI, Port, sftpModelShared.Usuario,
                                           sftpModelShared.PrivateKey);
            }

            string current = "//" + sftpInfo.DiretorioInspecao + "//" + "LOG" + "//";


            using (SftpClient client = tmpClient)
            {
                try
                {
                    client.Connect();

                    var d = client.Exists(current);
                    if (!d)
                    {
                        client.CreateDirectory(current);
                    }
                }

                catch
                {
                    throw new Exception(string.Format("Erro ao criar pasta LOG para o organismo {0}", sftpInfo.DiretorioInspecaoLocal));
                }

                client.Disconnect();
            }
        }
示例#42
0
文件: Program.cs 项目: Redyenx/QSSH
 private static void UploadFileToSFTP(IEnumerable <string> filePaths)
 {
     try
     {
         using var client = new SftpClient(_host, _port, _user, _password);
         client.Connect();
         var i = client.ConnectionInfo;
         if (client.IsConnected)
         {
             Console.WriteLine($"Conectado a: {i.Host}");
             if (_log)
             {
                 Logger.Logger.i($"Conectado a: {i.Host}");
             }
             foreach (var filePath in filePaths)
             {
                 using var fileStream = new FileStream(filePath, FileMode.Open);
                 client.BeginUploadFile(fileStream, Path.GetFileName(filePath), null, null);
                 Console.WriteLine("Archivo enviado: {0} ({1:N0} bytes)", filePath, fileStream.Length);
                 if (_log)
                 {
                     Logger.Logger.i($"Archivo enviado: {filePath}");
                 }
                 client.BufferSize = 4 * 1024; // bypass Payload error large files
                 client.UploadFile(fileStream, Path.GetFileName(filePath));
             }
             client.Disconnect();
             Console.WriteLine($"Desconectado de: {i.Host}");
             if (_log)
             {
                 Logger.Logger.i($"Desconectado de: {i.Host}");
             }
         }
         else
         {
             Debug.WriteLine("No se pudo conectar al cliente.");
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
示例#43
0
        /// <summary>
        /// Sends the file to virtual machine using SSH.NET SFTP.
        /// </summary>
        /// <param name="hostname">The hostname.</param>
        /// <param name="port">The port.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="localFilesPath">The local files path.</param>
        /// <param name="remotePath">The remote path.</param>
        /// <returns></returns>
        public static string SendFileSftp(string hostname, int port, string username, string password, List <string> localFilesPath, string remotePath)
        {
            SftpClient client;

            try
            {
                client = new SftpClient(hostname, port, username, password);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return("Cannot create client");
            }

            try
            {
                using (client)
                {
                    client.Connect();
                    client.BufferSize = 4 * 1024;
                    foreach (string filePath in localFilesPath)
                    {
                        string fname = filePath;
                        //new FileInfo(filePath).ToString();

                        //var fileStream = new FileStream(fname, FileMode.Open);
                        FileStream fileStream  = File.OpenRead(fname);
                        var        destination =
                            $"{remotePath}/{new FileInfo(filePath).Name}";
                        client.UploadFile(fileStream, destination, true, null);
                        logger.Info("Uploaded: {0}", destination);
                    }

                    client.Disconnect();
                    client.Dispose();
                    return("Uploaded");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return("Cannot upload");
            }
        }
示例#44
0
        public static void DownloadDirectoryFile()
        {
            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}开始下载文件");

            var remoteDirectory = Options.RemoteDir;
            var localDirectory  = Options.LocalDir;
            var localFiles      = new DirectoryInfo(localDirectory).GetFiles("*.zip");

            using var sftp = new SftpClient(Options.Host, Convert.ToInt32(Options.Port), Options.UserName, Options.Password);
            try
            {
                sftp.Connect();
                var files = sftp.ListDirectory(remoteDirectory);

                var addedFile = 0;
                foreach (var file in files)
                {
                    if (file.IsDirectory)
                    {
                        continue;
                    }
                    if (localFiles.Any(c => c.Name == file.Name))
                    {
                        continue;
                    }

                    addedFile++;
                    Console.WriteLine($"新增文件【{file.FullName}】");
                    if (!file.IsDirectory && !file.IsSymbolicLink)
                    {
                        DownloadFile(sftp, file, Options.LocalDir);
                        //var fullPath = Options.LocalDir + file.FullName;
                        //FileServices.ProcessData(fullPath);
                    }
                }
                Console.WriteLine($"共新增文件{addedFile}");
                sftp.Disconnect();
            }
            catch (Exception e)
            {
                //LogsHelper.WriteLogToFile(e.ToString(), "DownloadDirectoryErr", ".txt");
                Console.WriteLine("DownloadDirectoryErr:" + e.Message);
            }
        }
示例#45
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        var localPath = @HttpContext.Current.Server.MapPath("~/cdrs/");
        var keyFile   = new PrivateKeyFile(@HttpContext.Current.Server.MapPath("~/path-to.ppk"), "password");
        var keyFiles  = new[] { keyFile };
        var username  = "******";

        var methods = new List <AuthenticationMethod>();

        methods.Add(new PasswordAuthenticationMethod(username, "password"));
        methods.Add(new PrivateKeyAuthenticationMethod(username, keyFiles));


        var con = new ConnectionInfo("ftphost", 22, username, methods.ToArray());

        using (var client = new SftpClient(con))
        {
            client.Connect();

            var files = client.ListDirectory("/Cdrs/");
            foreach (var file in files)
            {
                if (file.Name.Contains("Daily") && file.Name.Contains("SIP") && file.Attributes.LastWriteTime.Date == DateTime.Today.AddDays(-1).Date)
                {
                    if (!File.Exists(localPath + file.Name))
                    {
                        //Debug.WriteLine(file);
                        using (var fs = new FileStream(localPath + file.Name, FileMode.Create))
                        {
                            client.DownloadFile(file.FullName, fs);
                            fs.Close();
                        }
                        ReadFiles();
                    }
                    else
                    {
                        Debug.WriteLine("File Already Exists!");
                    }
                }
            }

            client.Disconnect();
        }
    }
        public bool UploadFiles(List <string> localFilePaths, string remoteFolder)
        {
            var errorOccured = false;

            //Create a client
            using (var sftp = new SftpClient(Host, Port, Username, Password))
            {
                //Connect
                sftp.Connect();

                sftp.BufferSize = 4 * 1024;
                //Iterate the collection
                foreach (var localFilePath in localFilePaths)
                {
                    //Prepare vars
                    var fileInfo       = new FileInfo(localFilePath);
                    var remoteFilePath = remoteFolder.EndsWith("/") ? $"{remoteFolder}{fileInfo.Name}" : $"{remoteFolder}/{fileInfo.Name}";

                    try
                    {
                        //Open a filestream
                        using (var fileStream = new FileStream(localFilePath, FileMode.Open))
                        {
                            //...and upload the file
                            sftp.UploadFile(fileStream, remoteFilePath, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        errorOccured = true;
                        logger.Error(ex.Message, ex);
                        if (ThrowErrors)
                        {
                            throw new Exception($"zAppDev.DotNet.Framework SFTPClient error in uploading file: {fileInfo.Name}");
                        }
                    }
                }
                //Finally disconnect and dispose
                sftp.Disconnect();
            }

            return(!errorOccured);
        }
示例#47
0
        public bool Connect(bool ignoreLog = false)
        {
            try
            {
                if (!ignoreLog)
                {
                    _logger("ssh connecting " + Host + "... ", NLog.LogLevel.Info);
                }
                _sshClient.Connect();
                _sftpClient.Connect();
                if (_sshClient.IsConnected && _sftpClient.IsConnected)
                {
                    if (!ignoreLog)
                    {
                        RootFolder = _sftpClient.WorkingDirectory;
                        var _connectionInfo = _sshClient.ConnectionInfo;
                        if (_connectionInfo != null && !string.IsNullOrEmpty(_connectionInfo.Host))
                        {
                            _logger($"Connected to {_connectionInfo.Username}@{_connectionInfo.Host}:{_connectionInfo.Port} via SSH", NLog.LogLevel.Info);
                        }
                        else
                        {
                            _logger($"ssh connect success:{Host}", NLog.LogLevel.Info);
                        }
                    }
                    return(true);
                }

                if (!ignoreLog)
                {
                    _logger($"ssh connect fail", NLog.LogLevel.Error);
                }
                return(false);
            }
            catch (Exception ex)
            {
                if (!ignoreLog)
                {
                    _logger($"ssh connect fail:{ex.Message}", NLog.LogLevel.Error);
                }
                return(false);
            }
        }
示例#48
0
        public void Test_PasswordConnectionInfo()
        {
            var host     = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example PasswordConnectionInfo
            var connectionInfo = new PasswordConnectionInfo(host, username, password);
            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion

            Assert.AreEqual(connectionInfo.Host, Resources.HOST);
            Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
        }
示例#49
0
        static void SendFTPToKerlink(List <DataCommand> datas, string FileName = "data.json")
        {
            // Get the object used to communicate with the server.
            //sftp://192.168.8.105

            using (SftpClient client = new SftpClient(IPKerlinkGateway, 22, "admin", "spnpwd"))
            {
                client.Connect();
                client.ChangeDirectory("\tx_data");
                var JsonData = JsonConvert.SerializeObject(datas);

                //new FileStream(@"c:\temp\sample.json",FileMode.Open)
                using (var fs = GenerateStreamFromString(JsonData))
                {
                    client.BufferSize = 4 * 1024;
                    client.UploadFile(fs, FileName);
                }
            }
        }
示例#50
0
        /// <summary>
        ///     Create an SFTP client and connect to a server using configuration from the arguments.
        /// </summary>
        /// <param name="arguments">The arguments to use to connect to the SFTP server.</param>
        private static SftpClient CreateSftpClient(Arguments arguments)
        {
            int port;
            var server = arguments.SFTPServer.Split(':');

            try
            {
                port = int.Parse(server[1]);
            }
            catch (Exception)
            {
                port = 22;
            }

            var client = new SftpClient(server[0], port, arguments.UserName, arguments.UserPassword);

            client.Connect();
            return(client);
        }
示例#51
0
        public void Test_Sftp_Upload_Forbidden()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string remoteFileName   = "/root/1";

                this.CreateTestFile(uploadedFileName, 1);

                using (var file = File.OpenRead(uploadedFileName))
                {
                    sftp.UploadFile(file, remoteFileName);
                }

                sftp.Disconnect();
            }
        }
示例#52
0
        /// <summary>
        ///     Uploads a single demo, used for scheduled playtesting events.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private static async Task <bool> UploadDemo(FileInfo file)
        {
            using (var client = new SftpClient(_dataService.RSettings.ProgramSettings.DemoFtpServer,
                                               _dataService.RSettings.ProgramSettings.DemoFtpUser,
                                               _dataService.RSettings.ProgramSettings.DemoFtpPassword))
            {
                try
                {
                    client.Connect();
                }
                catch (Exception e)
                {
                    await _log.LogMessage(
                        $"Failed to connect to SFTP server. {_dataService.RSettings.ProgramSettings.DemoFtpServer}" +
                        $"\n {e.Message}", alert : true, color : LOG_COLOR);

                    return(false);
                }

                try
                {
                    client.ChangeDirectory(_dataService.RSettings.ProgramSettings.DemoFtpPath);

                    using (var fileStream = File.OpenRead(file.FullName))
                    {
                        client.UploadFile(fileStream, file.Name, true);
                    }
                }
                catch (Exception e)
                {
                    await _log.LogMessage(
                        $"Failed to download file from playtest server. {_dataService.RSettings.ProgramSettings.DemoFtpServer}" +
                        $"\n{e.Message}", alert : true, color : LOG_COLOR);

                    return(false);
                }

                client.Disconnect();
            }

            _ = _log.LogMessage($"Uploaded {file.FullName} to server where it can be viewed.", color: LOG_COLOR);
            return(true);
        }
示例#53
0
文件: FTP.cs 项目: mgheffel/Conduit
        /*Button click to send a zipped file to Beocat
         * Once clicked an open file dialog appears to select the file to send
         * Then a sftp client is created and then it is used to connect to the Beocat server
         * Next a FileStream object is used to stream the file and upload it to Beocat.
         * A messagebox then shows the file was added successfully
         * Last the file is unzipped in Beocat using ssh and the unzip command
         */
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd      = new OpenFileDialog();
            string         filename = "";
            string         justName = "";

            //Get file name to upload
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                filename = ofd.FileName;
            }
            justName = Path.GetFileNameWithoutExtension(filename);
            //Create client Object
            using (SftpClient sftpClient = new SftpClient(getSftpConnection("headnode.beocat.ksu.edu", m.user, 22, m.password)))
            {
                //Connect to server
                sftpClient.Connect();
                //Create FileStream object to stream a file
                using (FileStream fs = new FileStream(filename, FileMode.Open))
                {
                    sftpClient.BufferSize = 1024;
                    sftpClient.UploadFile(fs, Path.GetFileName(filename));
                }

                sftpClient.Dispose();
            }
            MessageBox.Show("File successfully added");

            //sshClient to unzip the newly added zipfile
            SshClient ssh = new SshClient("headnode.beocat.ksu.edu", m.user, m.password);

            if (ssh != null)
            {
                using (ssh)
                {
                    ssh.Connect();
                    string file2upzip = "unzip " + justName + ".zip";
                    var    command    = ssh.CreateCommand("unzip " + justName + ".zip");
                    command.Execute();
                }
                ssh.Disconnect();
            }
        }
示例#54
0
        public override string tryGetFileFromGuest(string srcpath, out Exception errorOrNull)
        {
            try
            {
                using (SftpClient client = new SftpClient(inf))
                {
                    client.Connect();

                    string toRet = client.ReadAllText(srcpath);
                    errorOrNull = null;
                    return(toRet);
                }
            }
            catch (Exception e)
            {
                errorOrNull = e;
                return(null);
            }
        }
示例#55
0
        /// <summary>
        /// List a remote directory in the console.
        /// </summary>
        public static IEnumerable <SftpFile> ListFiles(string host, string username, string password, string remotedir)
        {
            using (SftpClient sftp = new SftpClient(host, username, password))
            {
                try
                {
                    sftp.Connect();
                    var files = sftp.ListDirectory(remotedir);

                    sftp.Disconnect();
                    return(files);
                }
                catch (Exception e)
                {
                    return(null);
                    // Console.WriteLine("An exception has been caught " + e.ToString());
                }
            }
        }
示例#56
0
        public async Task <string> DownloadFile(string serverFilePath, string serverFileName)
        {
            SftpClient client = new SftpClient(_hostName, _userName, _password);

            client.Connect();
            client.ChangeDirectory(serverFilePath);

            if (!Directory.Exists(_downloadDirectory))
            {
                Directory.CreateDirectory(_downloadDirectory);
            }

            using (Stream serverOrderPDF = File.OpenWrite(_downloadDirectory + serverFileName))
            {
                client.DownloadFile(serverFileName, serverOrderPDF);
            }

            return(_downloadDirectory + serverFileName);
        }
        public void Test_BaseClient_IsConnected_True_After_Disconnect()
        {
            // 2012-04-29 - Kenneth_aa
            // The problem with this test, is that after SSH Net calls .Disconnect(), the library doesn't wait
            // for the server to confirm disconnect before IsConnected is checked. And now I'm not mentioning
            // anything about Socket's either.

            var connectionInfo = new PasswordAuthenticationMethod(Resources.USERNAME, Resources.PASSWORD);

            using (SftpClient client = new SftpClient(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                Assert.AreEqual<bool>(true, client.IsConnected, "IsConnected is not true after Connect() was called.");

                client.Disconnect();

                Assert.AreEqual<bool>(false, client.IsConnected, "IsConnected is true after Disconnect() was called.");
            }
        }
        public void Test_BaseClient_IsConnected_True_After_Disconnect()
        {
            // 2012-04-29 - Kenneth_aa
            // The problem with this test, is that after SSH Net calls .Disconnect(), the library doesn't wait
            // for the server to confirm disconnect before IsConnected is checked. And now I'm not mentioning
            // anything about Socket's either.

            var connectionInfo = new PasswordAuthenticationMethod(Resources.USERNAME, Resources.PASSWORD);

            using (SftpClient client = new SftpClient(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                Assert.AreEqual<bool>(true, client.IsConnected, "IsConnected is not true after Connect() was called.");

                client.Disconnect();

                Assert.AreEqual<bool>(false, client.IsConnected, "IsConnected is true after Disconnect() was called.");
            }
        }
示例#59
0
 //http://blog.deltacode.be/2012/01/05/uploading-a-file-using-sftp-in-c-sharp/
 public void UploadFile(string sourceFilePath, string sftpWorkingDirectory)
 {
     using (SftpClient client = new SftpClient(_host, _port, _userName, _password))
     {
         Console.WriteLine("Connecting to {0}:{1}", _host, _port);
         client.Connect();
         Console.WriteLine("Changing directory to {0} ...", sftpWorkingDirectory);
         client.ChangeDirectory(sftpWorkingDirectory);
         using (FileStream fileStream = new FileStream(sourceFilePath, FileMode.Open))
         {
             string fileName = Path.GetFileName(sourceFilePath);
             Console.WriteLine("Uploading {0} ...", sourceFilePath);
             client.BufferSize = 4 * 1024; // bypass Payload error large files
             client.UploadFile(fileStream, fileName);
         }
         Console.WriteLine("Disconnecting from {0} ...", _host, _port);
         client.Disconnect();
     }
 }
示例#60
0
 static void Main(string[] args)
 {
     using (SftpClient sftpClient = new SftpClient(host, username, password))
     {
         try
         {
             sftpClient.Connect();
             sftpClient.DeleteFile("./variables.txt");
             sftpClient.Create("./variables.txt");
             sftpClient.WriteAllText("./variables.txt", "testwrite");
             sftpClient.ReadAllText("./variables.txt");
             sftpClient.Disconnect();
         }
         catch (Exception e)
         {
             Console.WriteLine("An exception has been caught " + e.ToString());
         }
     }
 }