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_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();
            }
        }
        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_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_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);
        }
Exemple #6
0
        public void Close()
        {
            FtpClient?.Disconnect();
            SftpClient?.Disconnect();
            try
            {
                StreamReader.Close();
            }
            catch
            {
            }
            Stream?.Close();

            if (!string.IsNullOrWhiteSpace(TempFilePath))
            {
                try
                {
                    File.Delete(TempFilePath);
                }
                catch (Exception e)
                {
                    Logger.Error(e, e.StackTrace);
                }
            }
        }
 //Dispose implementation & Destructor
 public void Dispose()
 {
     _sftpClient?.Disconnect();
     _sftpClient?.Dispose();
     _sshClient?.Disconnect();
     _sshClient?.Dispose();
 }
        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();
        }
Exemple #9
0
#pragma warning restore AsyncFixer01 // Unnecessary async/await usage

        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                _client?.Disconnect();
                _client?.Dispose();
            }
        }
 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_BeginUploadFile_FileNameIsWhiteSpace()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         sftp.BeginUploadFile(new MemoryStream(), "   ", null, null);
         sftp.Disconnect();
     }
 }
Exemple #12
0
        public void Close()
        {
            if (verboseLogging)
            {
                Trace.TraceInformation($"Disconnecting from {service.HostName}:{service.Port}");
            }
            client?.Disconnect();

            Trace.TraceInformation($"Disconnected from {service.HostName}:{service.Port}");
        }
        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();
            }
        }
Exemple #14
0
    public string GetDirectoryContent()
    {
        if (password == null || password.Length < 1)
        {
            if (debug)
            {
                Debug.LogError("sftpaccess >> No Password specified!");
            }
            return(null);
        }
        using (var client = new SftpClient(host, username, password))
        {
            client.Connect();
            if (debug)
            {
                Debug.Log("Is connected? " + client.IsConnected);
            }

            string baseReadWriteDir = "/surveylog/";
            string playerName       = PlayerPrefs.GetString("name");

            //check if /$name exists, if not create it, then switch the workdir
            client.ChangeDirectory(baseReadWriteDir);
            if (!client.Exists(playerName))
            {
                client.CreateDirectory(playerName);
            }
            client.ChangeDirectory(playerName);
            //check if /$name/$type exists, if not create it, then switch the workdir
            if (!client.Exists(gameTypeString))
            {
                client.CreateDirectory(gameTypeString);
            }
            client.ChangeDirectory(gameTypeString);

            Console.WriteLine("Changed directory to {0}", baseReadWriteDir);
            // no. of files currently
            List <SftpFile> files = client.ListDirectory(client.WorkingDirectory).ToList();
            client.Disconnect();
            String ret = "";
            foreach (var item in files)
            {
                if (debug)
                {
                    Debug.Log(">>" + item);
                }
                if (!item.Name.StartsWith("."))
                {
                    ret += "> " + item.Name + "\r\n";
                }
            }
            return(ret);
        }
    }
Exemple #15
0
        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();
            }
        }
        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();
            }
        }
        private static void Upload_Hankook_One_Purchases(SqlConnection connection, string filePath, string fileName)
        {
            string logFileName, host, username, password;

            //string downloadFileName;
            try
            {
                logFileName = filePath + fileName;
                host        = "sftp.channel-fusion.com";
                username    = "******";
                password    = "******";
                //downloadFileName = "ack_309354_" + logFileYear + logFileMonth + logFileDay + ".csv";
                //host = "fxserver.360incentives.com";
                //username = "******";
                //password = "******";

                using (var client = new SftpClient(host, 22, username, password))
                {
                    client.Connect();

                    Console.WriteLine("Connected to {0}", host);

                    //client.ChangeDirectory("/in/");

                    //Console.WriteLine("Changed directory to {0}", workingdirectory);

                    using (var fileStream = new FileStream(logFileName, FileMode.Open))
                    {
                        //Console.WriteLine("Uploading {0} ({1:N0} bytes)", logFileName, fileStream.Length);

                        client.BufferSize = 4 * 1024; // bypass Payload error large files

                        client.UploadFile(fileStream, Path.GetFileName(logFileName));
                    }
                    Console.WriteLine("Status update {0}", logFileName + " has been uploaded");
                    FileInfo newFile = new FileInfo(filePath + "Hankook_One.csv");
                    if (newFile.Exists)
                    {
                        newFile.Delete();
                    }
                    FileInfo File = new FileInfo(filePath + fileName);
                    File.CopyTo(filePath + "Hankook_One.csv");
                    client.Disconnect();
                }
                Update_Hankook_One_Dealer(connection);
                //System.Environment.Exit(0);
                //Application.Exit();
            }
            catch (Exception error)
            {
                string msg = "GBSQL01v2\nWhile uploading HK One units file " + error.Message;
                Email_Notification("*****@*****.**", "Hankook One Upload Error", msg);
            }
        }
        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_ChangeDirectory_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.ChangeDirectory(null);

                sftp.Disconnect();
            }
        }
        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();
            }
        }
Exemple #21
0
 /// <summary>
 /// Disconnect our client
 /// </summary>
 public static void Disconnect()
 {
     if (FTP)
     {
         ftpc.Close();
     }
     else
     {
         sftpc.Disconnect();
     }
 }
        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_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_ChangeDirectory_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.ChangeDirectory(null);

                sftp.Disconnect();
            }
        }
        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();
            }
        }
Exemple #28
0
        /// <summary>
        /// £¹czy siê z endpointem i pobiera wszystkie pliki póŸniejsze ni¿ data ostatniego pobrania
        /// </summary>
        /// <param name="log">Informacja o skopiowanych plikach</param>
        /// <returns>Tablice nazw pobranych plików oraz ich rozmiarów</returns>
        public bool Download(ref FtpSyncModel log)
        {
            if (!CheckLocalDirectory() || !CheckDispatcher())
            {
                return(false);
            }

            Connect();

            var lsFileNames = new List <string>();
            var llFileSizes = new List <long>();
            var ldFileDates = new List <DateTime>();
            var files       = m_sftpClient.ListDirectory(m_sRemoteDir).Where(f => f.IsRegularFile).ToArray();

            foreach (SftpFile f in files)
            {
                if (GetFile(f))
                {
                    lsFileNames.Add(f.Name);
                    llFileSizes.Add(f.Length);
                    ldFileDates.Add(f.LastWriteTime);
                    if (m_showError != null)
                    {
                        m_showError(eSeverityCode.FileInfo, $"1|{f.Name}|{f.Length}|{f.LastWriteTime.ToBinary()}");
                    }
                }
            }

            if (m_Disp != null && !m_Disp.InProgress && m_showError != null)
            {
                m_showError(eSeverityCode.Message, $"Pobieranie z serwera {m_sHost}{m_sRemoteDir} zosta³o przerwane przez u¿ytkownika");
            }

            m_sftpClient.Disconnect();

            log.fileNames = lsFileNames.ToArray();
            log.fileSizes = llFileSizes.ToArray();
            log.fileDates = ldFileDates.ToArray();

            return(true);
        }
        public void Disconnect()
        {
            if (Protocol == SSHTransferProtocol.SCP)
            {
                ScpClt.Disconnect();
            }

            if (Protocol == SSHTransferProtocol.SFTP)
            {
                SftpClt.Disconnect();
            }
        }
Exemple #30
0
        /// <summary>
        /// Connects to the client SFTP server, calls the method to get the files
        /// </summary>
        /// <returns>boolean if connection succeeded</returns>
        public void Connect()
        {
            Boolean Connected = false;
            string  error     = "";

            while (!Connected && attemptCounter < maxRetries)
            {
                try
                {
                    var connectionInfo = new ConnectionInfo(servername, serverport, ConfigurationManager.AppSettings["username"],
                                                            new PasswordAuthenticationMethod(
                                                                ConfigurationManager.AppSettings["username"],
                                                                ConfigurationManager.AppSettings["password"]
                                                                ));

                    using (var client = new SftpClient(connectionInfo))
                    {
                        client.Connect();
                        if (client.IsConnected)
                        {
                            GetFile(client);
                            Connected = true;
                            client.Disconnect();
                        }
                    }
                    attemptCounter = 0;
                }
                // catch and write authentication errors (this error occurs even if the password is correct)
                catch (SshAuthenticationException e)
                {
                    attemptCounter++;
                    error += "Renci.SshNet.Common.SshAuthenticationException: Permission denied (password).\n";
                    if (attemptCounter >= maxRetries)
                    {
                        using (EventLog eventLog = new EventLog("Application"))
                        {
                            eventLog.Source = "Application Error";
                            eventLog.WriteEntry("Connection to Esker SFTP server" + servername + ":" + serverport + error + "Exceeded maximum amount of retries: " + maxRetries + "\n retrying in 5 minutes.", EventLogEntryType.Information, 1000, 100);
                        }
                    }
                }
                // catch and write other exceptions
                catch (Exception e)
                {
                    attemptCounter++;
                    using (EventLog eventLog = new EventLog("Application"))
                    {
                        eventLog.Source = "Application Error";
                        eventLog.WriteEntry("Connection to Esker SFTP server" + servername + ":" + serverport + ". \n" + e.ToString(), EventLogEntryType.Error, 1000, 100);
                    }
                }
            }
        }
Exemple #31
0
 /// <summary>
 ///  Closes the SFTP Connection
 /// </summary>
 public void CloseConnection()
 {
     try
     {
         client.Disconnect();
         _logger.LogInformation($"Disconnected from [{_config.Host}]");
     }
     catch (Exception exception)
     {
         _logger.LogError(exception, $"Failed closing SSH Connection to [{_config.Host}]");
     }
 }
Exemple #32
0
 public byte[] DownloadDocAttachment(int docAttachmentId, string docAttachmentFileName)
 {
     using (SftpClient client = new SftpClient(connectionInfo))
     {
         client.Connect();
         string       filePath = this.root + "/" + docAttachmentId.ToString() + "_" + docAttachmentFileName;
         MemoryStream ms       = new MemoryStream();
         client.DownloadFile(filePath, ms);
         client.Disconnect();
         return(ms.ToArray());
     }
 }
Exemple #33
0
        public override void Delete(FileInf file)
        {
            using (var client = new SftpClient(GetConnectionInfo()))
            {
                client.Connect();
                client.ChangeDirectory(Path);

                client.DeleteFile(file.Path);

                client.Disconnect();
            }
        }
Exemple #34
0
        public static void DeleteRemoteFile(string host, string file, string username, string password)
        {
            using (var sftp = new SftpClient(host, username, password))
            {
                sftp.Connect();

                sftp.Delete(file);

                sftp.Disconnect();

            }
        }
 public static int Send(string fileName)
 {
     using (var sftp = new SftpClient(host, port, username, new PrivateKeyFile(privateKeyFileName))){
         sftp.Connect();
         sftp.ChangeDirectory(remotePath);
         using (var uplfileStream = System.IO.File.OpenRead(fileName)){
             sftp.UploadFile(uplfileStream, fileName, true);
         }
         sftp.Disconnect();
     }
     return(0);
 }
Exemple #36
0
        /* ONE CONNECTION PER INSTANCE */
        private void disconnectSftp()
        {
            if (persistConnection)
            {
                return;
            }

            if (sftpClient != null)
            {
                sftpClient.Disconnect();
            }
        }
Exemple #37
0
 /// <summary>
 ///     Disconnect
 /// </summary>
 /// <returns></returns>
 public bool Disconnect()
 {
     try
     {
         _client.Disconnect();
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
 public void ConnectToSSHServerUsingPassword()
 {
     using (SftpClient sftp = new SftpClient(SSH_HOST_NAME, SSH_PORT, SSH_USER_NAME, SSH_PASSWORD))
     {
         sftp.Connect();
         var files = sftp.ListDirectory(string.Empty);
         foreach (var file in files)
         {
         }
         sftp.Disconnect();
     }
 }
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     if (_disposed)
     {
         return;
     }
     _sshclient.Disconnect();
     _sftpClient.Disconnect();
     _sftpClient.Dispose();
     _sshclient.Dispose();
     _disposed = true;
 }
        public void Dispose()
        {
            if (_sftpClient != null)
            {
                if (_sftpClient.IsConnected)
                {
                    _sftpClient.Disconnect();
                }

                _sftpClient.Dispose();
            }
        }
Exemple #41
0
        public static void DeleteRemoteDirectory(string host, string directory, string username, string password)
        {
            using (var sftp = new SftpClient(host, username, password))
            {
                sftp.Connect();

                sftp.DeleteDirectory(directory);

                sftp.Disconnect();

            }
        }
Exemple #42
0
        public void send()
        {
            log.append("Loading files to send to SFTP");
            String[] files = System.IO.Directory.GetFiles(sendFiles, "*.csv");

            try
            {
                client.Connect();
                client.ChangeDirectory("put");
                log.append("Sucessfully opened put folder");
            }
            catch (Exception e)
            {
                successfulConnection = false;
                log.append("Unable to upload files to FTP Server: error connection to FTP server");
            }


            if (successfulConnection)
            {
                for (int i = 0; i < files.Length; i++)
                {
                    fileStream = new FileStream(files[i], FileMode.Open);
                    client.UploadFile(fileStream, Path.GetFileName(files[i]));
                    log.append("Coppied file " + Path.GetFileName(files[i]) + "to SFTP server");
                    fileStream.Close();
                }
                client.Disconnect();

                for (int i = 0; i < files.Length; i++)
                {
                    if (System.IO.File.Exists(archiveDirectory + Path.GetFileName(files[i])))
                    {
                        System.IO.File.Delete(archiveDirectory + Path.GetFileName(files[i]));
                    }
                    File.Move(files[i], archiveDirectory + Path.GetFileName(files[i]));
                    log.append("Moved file " + Path.GetFileName(files[i]) + " to archive directory");
                }
            }
        }
        public static int CheckFileExistsSFTP(string fileName, string location, string extension, string host, int port, string username, string password)
        {
            var path = GetFileNameAndExt(fileName).FirstOrDefault();
            var ext  = path.Key;
            var fn   = path.Value;

            using (SftpClient sftp = new SftpClient(host, port, username, password))
            {
                try
                {
                    if (string.IsNullOrEmpty(ext))
                    {
                        fileName = string.Format("*{0}*{1}", fn, GetFileExtensions().FirstOrDefault(f => f.Key == extension).Value);
                    }
                    else
                    {
                        fileName = string.Format("*{0}*{1}", fn, ext);
                    }

                    sftp.Connect();

                    //var files = sftp.ListDirectory(location);
                    //sftp.ChangeDirectory("/");
                    var files = sftp.ListDirectory(string.Format("{0}/{1}", location, fileName));

                    //sftp.Exists(string.Format("{0}/{1}", location, fileName));

                    var count = files.Count();

                    sftp.Disconnect();

                    return(count);
                }
                catch (Exception ex)
                {
                    sftp.Disconnect();
                    return(0);
                }
            }
        }
Exemple #44
0
        private void Connect_Sftp(string host, int port, string user, string passwd, string tomcat_doc, string filePath)
        {
            SftpClient sFtp    = new SftpClient(host, port, user, passwd);
            FileStream fStream = null;

            try
            {
                sFtp.ConnectionInfo.Timeout = TimeSpan.FromSeconds(120);

                sFtp.Connect();

                sFtp.ChangeDirectory(tomcat_doc + "/webapps/");

                if (sFtp.Exists(Path.GetFileName(filePath)))
                {
                    sFtp.Delete(Path.GetFileName(filePath));
                }

                fStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

                progressBar1.Invoke((MethodInvoker) delegate { progressBar1.Maximum = (int)fStream.Length; });

                sFtp.BufferSize = 4 * 1024;

                sFtp.UploadFile(fStream, Path.GetFileName(filePath), UpdateProgresBar);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                this.Invoke((MethodInvoker) delegate { label15.Text = "파일업로드 오류"; });
                sFtp.Disconnect();
                fStream.Close();
            }
            finally
            {
                sFtp.Disconnect();
                fStream.Close();
            }
        }
        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();
            }
        }
        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();
            }
        }
        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();
            }
        }
        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();
            }
        }
        public void Test_Sftp_Download_Forbidden()
        {
            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();

                string remoteFileName = "/root/.profile";

                using (var ms = new MemoryStream())
                {
                    sftp.DownloadFile(remoteFileName, ms);
                }

                sftp.Disconnect();
            }
        }
        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_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);
        }
        public void Test_Sftp_Upload_And_Download_1MB_File()
        {
            RemoveAllFiles();

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

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

                this.CreateTestFile(uploadedFileName, 1);

                //  Calculate has value
                var uploadedHash = CalculateMD5(uploadedFileName);

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

                string downloadedFileName = Path.GetTempFileName();

                using (var file = File.OpenWrite(downloadedFileName))
                {
                    sftp.DownloadFile(remoteFileName, file);
                }

                var downloadedHash = CalculateMD5(downloadedFileName);

                sftp.DeleteFile(remoteFileName);

                File.Delete(uploadedFileName);
                File.Delete(downloadedFileName);

                sftp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
        public void Test_Sftp_BeginSynchronizeDirectories()
        {
            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 asyncResult = sftp.BeginSynchronizeDirectories(sourceDir,
                    destDir,
                    searchPattern,
                    null,
                    null
                );

                // Wait for the WaitHandle to become signaled.
                asyncResult.AsyncWaitHandle.WaitOne(1000);

                var upLoadedFiles = sftp.EndSynchronizeDirectories(asyncResult);

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

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

                // Close the wait handle.
                asyncResult.AsyncWaitHandle.Close();

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

            #region Example PasswordConnectionInfo AuthenticationBanner
            var connectionInfo = new PasswordConnectionInfo(host, username, password);
            connectionInfo.AuthenticationBanner += delegate(object sender, AuthenticationBannerEventArgs e)
            {
                Console.WriteLine(e.BannerMessage);
            };
            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_Change_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");

                sftp.CreateDirectory("test1");

                sftp.ChangeDirectory("test1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");

                sftp.CreateDirectory("test1_1");
                sftp.CreateDirectory("test1_2");
                sftp.CreateDirectory("test1_3");

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

                Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}", sftp.WorkingDirectory)));

                sftp.ChangeDirectory("test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("../test1_2");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");

                sftp.ChangeDirectory("..");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");

                sftp.ChangeDirectory("..");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");

                files = sftp.ListDirectory("test1/test1_1");

                Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}/test1/test1_1", sftp.WorkingDirectory)));

                sftp.ChangeDirectory("test1/test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("/home/tester/test1/test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("/home/tester/test1/test1_1/../test1_2");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");

                sftp.ChangeDirectory("../../");

                sftp.DeleteDirectory("test1/test1_1");
                sftp.DeleteDirectory("test1/test1_2");
                sftp.DeleteDirectory("test1/test1_3");
                sftp.DeleteDirectory("test1");

                sftp.Disconnect();
            }
        }
Exemple #58
0
            // get file from SFTP and return string
            public void getFromSFTP(string hostname, int port, string userName, string password, string tempFileName, string fileName)
            {
            try
            {
                mySFTPClient = new SftpClient(hostname, port, userName, password);
                myFileStream = new FileStream(tempFileName, FileMode.Create);

                mySFTPClient.Connect();
                mySFTPClient.DownloadFile(fileName, myFileStream, DownloadDone); // DownloadDone is Action<ulong>

                return;
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Document.getFromSFTP() Exception {0}", e);
                CrestronConsole.PrintLine("Document.getFromSFTP() Host {0}, Port {1}, User {2}, fileName {3}",
                                            hostname, port, userName, fileName);
                throw;
            }
            finally
            {
                mySFTPClient.Disconnect();
                myFileStream.Close();
            }
            }
Exemple #59
0
        // get file from SFTP and return string
        public void getFromSFTP(string url)
        {
            try
            {
                myFileStream = new FileStream(@"\NVRAM\temp.txt", FileMode.Create);
                mySFTPClient = new SftpClient(url, 22, "Crestron", "");

                mySFTPClient.Connect();
                mySFTPClient.DownloadFile(url, myFileStream, DownloadDone);

                return;
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Exception {0}", e);
                return;
            }
            finally
            {
                mySFTPClient.Disconnect();
                myFileStream.Close();
            }
        }
        public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each()
        {
            var maxFiles = 10;
            var maxSize = 5;

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

                var testInfoList = new Dictionary<string, TestInfo>();

                for (int i = 0; i < maxFiles; i++)
                {
                    var testInfo = new TestInfo();
                    testInfo.UploadedFileName = Path.GetTempFileName();
                    testInfo.DownloadedFileName = Path.GetTempFileName();
                    testInfo.RemoteFileName = Path.GetRandomFileName();

                    this.CreateTestFile(testInfo.UploadedFileName, maxSize);

                    //  Calculate hash value
                    testInfo.UploadedHash = CalculateMD5(testInfo.UploadedFileName);

                    testInfoList.Add(testInfo.RemoteFileName, testInfo);
                }

                var uploadWaitHandles = new List<WaitHandle>();

                //  Start file uploads
                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];
                    testInfo.UploadedFile = File.OpenRead(testInfo.UploadedFileName);

                    testInfo.UploadResult = sftp.BeginUploadFile(testInfo.UploadedFile,
                        remoteFile,
                        null,
                        null) as SftpUploadAsyncResult;

                    uploadWaitHandles.Add(testInfo.UploadResult.AsyncWaitHandle);
                }

                //  Wait for upload to finish
                bool uploadCompleted = false;
                while (!uploadCompleted)
                {
                    //  Assume upload completed
                    uploadCompleted = true;

                    foreach (var testInfo in testInfoList.Values)
                    {
                        var sftpResult = testInfo.UploadResult;

                        if (!testInfo.UploadResult.IsCompleted)
                        {
                            uploadCompleted = false;
                        }
                    }
                    Thread.Sleep(500);
                }

                //  End file uploads
                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];

                    sftp.EndUploadFile(testInfo.UploadResult);
                    testInfo.UploadedFile.Dispose();
                }

                //  Start file downloads

                var downloadWaitHandles = new List<WaitHandle>();

                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];
                    testInfo.DownloadedFile = File.OpenWrite(testInfo.DownloadedFileName);
                    testInfo.DownloadResult = sftp.BeginDownloadFile(remoteFile,
                        testInfo.DownloadedFile,
                        null,
                        null) as SftpDownloadAsyncResult;

                    downloadWaitHandles.Add(testInfo.DownloadResult.AsyncWaitHandle);
                }

                //  Wait for download to finish
                bool downloadCompleted = false;
                while (!downloadCompleted)
                {
                    //  Assume download completed
                    downloadCompleted = true;

                    foreach (var testInfo in testInfoList.Values)
                    {
                        var sftpResult = testInfo.DownloadResult;

                        if (!testInfo.DownloadResult.IsCompleted)
                        {
                            downloadCompleted = false;
                        }
                    }
                    Thread.Sleep(500);
                }

                var hashMatches = true;
                var uploadDownloadSizeOk = true;

                //  End file downloads
                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];

                    sftp.EndDownloadFile(testInfo.DownloadResult);

                    testInfo.DownloadedFile.Dispose();

                    testInfo.DownloadedHash = CalculateMD5(testInfo.DownloadedFileName);

                    if (!(testInfo.UploadResult.UploadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes == testInfo.UploadResult.UploadedBytes))
                    {
                        uploadDownloadSizeOk = false;
                    }

                    if (!testInfo.DownloadedHash.Equals(testInfo.UploadedHash))
                    {
                        hashMatches = false;
                    }
                }

                //  Clean up after test
                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];

                    sftp.DeleteFile(remoteFile);

                    File.Delete(testInfo.UploadedFileName);
                    File.Delete(testInfo.DownloadedFileName);
                }

                sftp.Disconnect();

                Assert.IsTrue(hashMatches, "Hash does not match");
                Assert.IsTrue(uploadDownloadSizeOk, "Uploaded and downloaded bytes does not match");
            }
        }