Beispiel #1
0
    public static void SCPFileSender(UserProgram userProgram)
    {
        try
        {
            //choofdlog.Multiselect = true

            using (SshClient client = new SshClient("127.0.0.1", 10022, "lvuser", ""))
            {
                client.Connect();
                client.RunCommand("rm FRCUserProgram FRCUserProgram.jar"); // Delete existing files so the frc program chooser knows which to run
                client.Disconnect();
            }

            using (ScpClient client = new ScpClient("127.0.0.1", 10022, "lvuser", ""))
            {
                client.Connect();
                using (Stream localFile = File.OpenRead(userProgram.fullFileName))
                {
                    client.Upload(localFile, @"/home/lvuser/" + userProgram.targetFileName);
                }
                client.Disconnect();
            }
        }
        catch (Exception) {}
    }
Beispiel #2
0
        public StatusCode Open()
        {
            StatusCode retVal = StatusCode.SUCCEED_STATUS;

            try
            {
                if (client != null)
                {
                    if (client.IsConnected)
                    {
                        return(StatusCode.SUCCEED_STATUS);
                    }
                    else
                    {
                        client.Disconnect();
                        client = new ScpClient(connectionInformation);
                        client.Connect();
                    }
                }
                else
                {
                    client = new ScpClient(connectionInformation);
                    client.Connect();
                }
                return(StatusCode.SUCCEED_STATUS);
            }
            catch (Exception ex)
            {
                return(new Common.CommonStatusCode(Common.CommonStatusCode.SCP_CONNECT_ERROR, new object[] { connectionInformation.Host, connectionInformation.Username }, ex, Config, ApplicationID));
            }
        }
Beispiel #3
0
        /// <summary>
        /// Copy from source to target
        /// </summary>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            Debug.WriteLine("CopyCommand");

            var scp = new ScpClient(client.ConnectionInfo)
            {
                BufferSize = 8 * 1024
            };

            Debug.WriteLine("Connect");

            // Need this or we get Dropbear exceptions...
            scp.Connect();

            Debug.WriteLine("Upload");

            bool status = false;

            try
            {
                scp.Upload(new FileInfo(Source), Target);
                status = true;
            } catch (Exception e)
            {
                Logger.Warn("Exception in SCP transfer: " + e.Message);
            }

            Debug.WriteLine("Done");

            return(status);
        }
Beispiel #4
0
        public static void flash_px4(string firmware_file)
        {
            if (is_solo_alive)
            {
                using (SshClient client = new SshClient(Solo.soloip, 22, Solo.username, Solo.password))
                {
                    client.KeepAliveInterval = TimeSpan.FromSeconds(5);
                    client.Connect();

                    if (!client.IsConnected)
                    {
                        throw new Exception("Failed to connect ssh");
                    }

                    var retcode = client.RunCommand("rm -rf /firmware/loaded");

                    using (ScpClient scpClient = new ScpClient(client.ConnectionInfo))
                    {
                        scpClient.Connect();

                        if (!scpClient.IsConnected)
                        {
                            throw new Exception("Failed to connect scp");
                        }

                        scpClient.Upload(new FileInfo(firmware_file), "/firmware/" + Path.GetFileName(firmware_file));
                    }

                    var st = client.CreateShellStream("bash", 80, 24, 800, 600, 1024 * 8);

                    // wait for bash prompt
                    while (!st.DataAvailable)
                    {
                        System.Threading.Thread.Sleep(200);
                    }

                    st.WriteLine("loadPixhawk.py; exit;");
                    st.Flush();

                    StringBuilder output = new StringBuilder();

                    while (client.IsConnected)
                    {
                        var line = st.Read();
                        Console.Write(line);
                        output.Append(line);
                        System.Threading.Thread.Sleep(100);

                        if (output.ToString().Contains("logout"))
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                throw new Exception("Solo is not responding to pings");
            }
        }
Beispiel #5
0
        public static void DownloadDFLog(string source, string destination)
        {
            if (is_solo_alive)
            {
                using (SshClient client = new SshClient(Solo.soloip, 22, Solo.username, Solo.password))
                {
                    client.KeepAliveInterval = TimeSpan.FromSeconds(5);
                    client.Connect();

                    if (!client.IsConnected)
                    {
                        throw new Exception("Failed to connect ssh");
                    }

                    using (ScpClient scpClient = new ScpClient(client.ConnectionInfo))
                    {
                        scpClient.Connect();

                        if (!scpClient.IsConnected)
                        {
                            throw new Exception("Failed to connect scp");
                        }

                        scpClient.Downloading += ScpClient_Downloading;

                        scpClient.Download("/log/dataflash/" + source, new FileInfo(destination));
                    }
                }
            }
            else
            {
                throw new Exception("Solo is not responding to pings");
            }
        }
        public void Test_Scp_File_20_Parallel_Upload_Download()
        {
            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                var uploadFilenames = new string[20];
                for (int i = 0; i < uploadFilenames.Length; i++)
                {
                    uploadFilenames[i] = Path.GetTempFileName();
                    this.CreateTestFile(uploadFilenames[i], 1);
                }

                Parallel.ForEach(uploadFilenames,
                    (filename) =>
                    {
                        scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
                    });

                Parallel.ForEach(uploadFilenames,
                    (filename) =>
                    {
                        scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
                    });

                var result = from file in uploadFilenames
                             where
                                 CalculateMD5(file) == CalculateMD5(string.Format("{0}.down", file))
                             select file;

                scp.Disconnect();

                Assert.IsTrue(result.Count() == uploadFilenames.Length);
            }
        }
Beispiel #7
0
        private ScpClient Scp()
        {
            var scpClient = new ScpClient(GetConnectionInfo(sshConnection));

            scpClient.Connect();
            return(scpClient);
        }
Beispiel #8
0
 private ScpClient scpConnect()
 {
     if (cred.remoteHost == "" || cred.username == "" || cred.password == "")
     {
         logMessage("Please set username / password");
     }
     else
     {
         try
         {
             if (_scpClient == null)
             {
                 logMessage("Thread " + Thread.CurrentThread.ManagedThreadId + " opening new scp connection to " + cred.remoteHost);
                 ConnectionInfo ConnNfo = new ConnectionInfo(cred.remoteHost, cred.username,
                                                             new AuthenticationMethod[] { new PasswordAuthenticationMethod(cred.username, cred.password) });
                 _scpClient            = new ScpClient(ConnNfo);
                 _scpClient.BufferSize = 512 * 1024;
             }
             if (!_scpClient.IsConnected)
             {
                 _scpClient.Connect();
                 logMessage("Scp connected to " + cred.remoteHost);
             }
             return(_scpClient);
         }
         catch (Renci.SshNet.Common.SshException e)
         {
             logMessage(e.Message);
         }
     }
     return(null);
 }
Beispiel #9
0
        protected override int DoExecute(ITaskContextInternal context)
        {
            DoLogInfo($"Connecting to {_userName}@{_host}");
            string password = _password.GetPassword();

            using (ScpClient cl = new ScpClient(_host, _userName, password))
            {
                cl.Connect();
                foreach (SourceDestinationPair item in _items)
                {
                    DoLogInfo($"copy {item.Source}->{item.Destination}");

                    if (item.IsFile)
                    {
                        cl.Upload(new FileInfo(item.Source), item.Destination);
                    }
                    else
                    {
                        cl.Upload(new DirectoryInfo(item.Source), item.Destination);
                    }
                }

                cl.Disconnect();
                return(0);
            }
        }
        protected void Arrange()
        {
            var random = new Random();
            _fileName = CreateTemporaryFile(new byte[] {1});
            _connectionInfo = new ConnectionInfo("host", 22, "user", new PasswordAuthenticationMethod("user", "pwd"));
            _fileInfo = new FileInfo(_fileName);
            _path = random.Next().ToString(CultureInfo.InvariantCulture);
            _uploadingRegister = new List<ScpUploadEventArgs>();

            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _pipeStreamMock = new Mock<PipeStream>(MockBehavior.Strict);

            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.CreatePipeStream()).Returns(_pipeStreamMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Open());
            _channelSessionMock.InSequence(sequence)
                .Setup(
                    p => p.SendExecRequest(string.Format("scp -t \"{0}\"", _path))).Returns(false);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _pipeStreamMock.As<IDisposable>().InSequence(sequence).Setup(p => p.Dispose());

            _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args);
            _scpClient.Connect();
        }
Beispiel #11
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (ScpClient client = new ScpClient(hostname, username, password))
            {
                client.Connect();
                if (client.IsConnected)
                {
                    j = Nayta.GetCounter() - 1;
                    if (j > 0)

                    {
                        for (int i = j; i >= 0; i--)
                        {
                            address = "C:/Temp/" + Nayta.GetFileName(i);
                            if (!File.Exists(address))
                            {
                                using (Stream localFile = File.Create(address))
                                {
                                    client.Download("/home/pi/Pictures/" + Nayta.GetFileName(i), localFile);
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #12
0
        /// <summary>
        /// Downloads the directory.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="uid">The uid.</param>
        /// <param name="pwd">The password.</param>
        /// <param name="remotePath">The remote path.</param>
        /// <param name="localPath">The local path.</param>
        /// <param name="errOut">The error out.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        /// <example>
        /// SSHFileTransfer ssh = new SSHFileTransfer();<br/>
        /// ssh.CurrentFile += (sender, e) =><br/>
        ///    {<br/>
        /// Debug.Print(e);<br/>
        /// };<br/>
        /// ssh.UploadStatus += (sender, e) =><br/>
        /// {<br/>
        /// Debug.Print(e.ToString());<br/>
        /// };<br/>
        /// bool value = ssh.DownloadDirectory("testmachine", "root", "toor", "/root/Downloads/", "C:\Test\",out errOut);
        /// </example>
        public bool DownloadDirectory(string host, string uid, string pwd, string remotePath, string localPath, out string errOut)
        {
            bool bAns = false;
            errOut = @"";
            try
            {
                DirectoryInfo toPath = new DirectoryInfo(localPath);
                ConnectionInfo connectionInfo = new ConnectionInfo(host, uid, new PasswordAuthenticationMethod(uid, pwd), new PrivateKeyAuthenticationMethod(General.RsaKey));

                ScpClient client = new ScpClient(connectionInfo);

                client.Connect();

                client.Downloading += delegate (object sender, ScpDownloadEventArgs e)
                {
                    OnCurrentFile(e.Filename);
                    OnDownloadStatus(CalcPercentage(e.Downloaded, e.Size));
                };

                client.Download(remotePath, toPath);
                bAns = true;
                client.Disconnect();
            }
            catch (Exception e)
            {
                errOut = ErrorMessage("DownloadDirectory", e);
            }
            return bAns;
        }
Beispiel #13
0
        /// <summary>
        /// Upload a file to the connected server.
        /// </summary>
        /// <param name="fileinfo">Local file</param>
        /// <param name="newfile">Server upload full-qualified filename</param>
        public bool UploadFile(FileInfo fileinfo, string newfile)
        {
            bool retVal = false;

            if (!disposed && base.IsConnected)
            {
                using (ScpClient transfer = new ScpClient(base.ConnectionInfo))
                {
                    try
                    {
                        transfer.Connect();
                        transfer.OperationTimeout = new TimeSpan(0, 1, 0);
                        transfer.Upload(fileinfo, newfile);
                        retVal = true;
                    }
                    catch
                    {
                        retVal = false;
                    }
                    finally
                    {
                        transfer.Disconnect();
                    }
                }
            }
            return(retVal);
        }
Beispiel #14
0
        public static ScpClient CreateScpClient(string ip, string username, string password)
        {
            if (DefaultScpClient != null && DefaultScpClient.IsConnected)
            {
                return(DefaultScpClient);
            }

            var authenticationsMethods = new AuthenticationMethod[]
            {
                new NoneAuthenticationMethod(username)
            };

            var connectionInfo = new ConnectionInfo(ip, 22, username, authenticationsMethods);

            DefaultScpClient = new ScpClient(connectionInfo);

            if (DefaultScpClient.IsConnected)
            {
                return(DefaultScpClient);
            }

            DefaultScpClient.RemotePathTransformation = RemotePathTransformation.ShellQuote;
            DefaultScpClient.Connect();

            return(DefaultScpClient);
        }
Beispiel #15
0
        public bool DownloadLogAndLoss(WeightVersionModel weight, string destinationFolder)
        {
            try
            {
                if (string.IsNullOrEmpty(weight.LogPath) || string.IsNullOrEmpty(weight.LossFunctionPath))
                {
                    return(false);
                }
                var pk = new PrivateKeyFile(ApplicationConstant.PrivateKeyFilePath);
                //var folder = DateTime.Now.ToString(ApplicationConstant.DatetimeFormat);
                var destination   = new DirectoryInfo(destinationFolder);
                var logPath       = $"{ServerDetectConstant.ApiPath}/{weight.LogPath}";
                var lossPath      = $"{ServerDetectConstant.ApiPath}/{weight.LossFunctionPath}";
                var detectSertver = CommonService.GetUrlDetectServer();
                using (var client = new ScpClient(detectSertver, 22, ServerTrainConstant.Username, pk))
                {
                    client.Connect();

                    client.Download(logPath, destination);
                    client.Download(lossPath, destination);

                    client.Disconnect();
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Beispiel #16
0
        public string TakePicture()
        {
            //Setup the connection info to ssh into the pi
            var    connectionInfo     = new ConnectionInfo(host, username, new PasswordAuthenticationMethod(username, password));
            string databaseInsertPath = "";

            using (var client = new SshClient(connectionInfo)) //create the ssh client
            {
                client.Connect();

                client.RunCommand("cd /home/pi");             //cd into the directory where the python script is located
                client.RunCommand("sudo python PyCamPic.py"); //Run the python script to take a picture
            }

            using (var client = new ScpClient(host, username, password)) //Create client for file transfer
            {
                client.Connect();

                string fileName = DateTime.Now.ToFileTime() + ".jpg"; //Name the file with current datetime

                using (Stream localFile = File.Create(Path.Combine(imagesFolderPath, fileName)))
                {
                    client.Download(remoteFolderPath, localFile); //Download image from pi to local machine
                    databaseInsertPath = Path.Combine(imagesFolderPath, fileName);
                }
            }

            DbConnection dbc = DbConnection.GetInstance();

            dbc.InsertImage(cameraName, DateTime.Now.ToString(), databaseInsertPath); //Insert the new image into the database

            return(databaseInsertPath);
        }
Beispiel #17
0
        /// <summary>
        /// ListenPort
        /// </summary>
        /// <returns></returns>
        public string ListenPort()
        {
            Constants.log.Info("Entering ScpListener ListenPort Method!");
            string response = string.Empty;

            if (_scpClient == null && _connInfo == null)
            {
                Constants.log.Info("Calling ScpListener InitializeListener Method!");
                InitializeListener();
            }

            try
            {
                _scpClient = new ScpClient(_connInfo);
                _scpClient.Connect();
                _scpClient.Upload(new DirectoryInfo(this.Path), "/home/" + this.Path);
                response = "Uploaded successfully!";
            }
            catch (Exception ex)
            {
                Constants.log.Error(ex.Message);
                response = ex.Message;
            }

            Constants.log.Info("Exiting ScpListener ListenPort Method!");
            return(response);
        }
Beispiel #18
0
        private async void LoginClick(object sender, RoutedEventArgs arg)
        {
            await Task.Run(() =>
            {
                m_btnLogin.Dispatcher.Invoke(() => { m_btnLogin.IsEnabled = false; });

                m_passwd = m_pwBox.Password;
                m_ssh    = new SshClient(m_ip, m_user, m_passwd);
                m_ssh.ConnectionInfo.Timeout = TimeSpan.FromSeconds(3);
                m_scp = new ScpClient(m_ip, m_user, m_passwd);
                m_scp.ConnectionInfo.Timeout = TimeSpan.FromSeconds(3);
                try
                {
                    m_ssh.Connect();
                    m_scp.Connect();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    if (m_ssh.IsConnected)
                    {
                        m_ssh.Disconnect();
                    }
                    m_btnLogin.Dispatcher.Invoke(() => { m_btnLogin.IsEnabled = true; });
                    return;
                }
                OnLogin?.Invoke(this, arg);
            });
        }
Beispiel #19
0
        private List <string> SshAttempt(List <string> sensorPaths)
        {
            List <string> res = new List <string>();

            var connectionInfo = new ConnectionInfo("liedholm.dynamic-dns.net",
                                                    2210,
                                                    "pi",
                                                    new PrivateKeyAuthenticationMethod("pi", new PrivateKeyFile(Settings.Default.opensshppk)));

            using (var client = new ScpClient(connectionInfo))
            {
                client.Connect();
                foreach (string sensorPath in sensorPaths)
                {
                    using (var stream = new MemoryStream())
                    {
                        client.Download(sensorPath, stream);
                        res.Add(Encoding.UTF8.GetString(stream.ToArray()));
                        Console.WriteLine(res.Last());
                    }
                }
            }

            return(res);
        }
Beispiel #20
0
        /// <summary>
        /// Commit the changes and upload them to the server
        /// </summary>
        public String Commit()
        {
            if (_config.Settings.Enabled)
            {
                ConnectionInfo connInfo = new ConnectionInfo(
                    _config.Settings.Server,
                    _config.Settings.ScpUsername,
                    AuthMethod);

                try
                {
                    using (var client = new ScpClient(connInfo))
                    {
                        client.Connect();
                        if (client.IsConnected)
                        {
                            var originalFileMS = new MemoryStream();
                            try
                            {
                                client.Download(_config.Settings.FilePath, originalFileMS);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"{_config.Settings.FilePath}: File Check Failed ({e.Message})");
                            }

                            MemoryStream newDataStream = new MemoryStream();
                            UTF8Encoding encoding      = new UTF8Encoding();
                            newDataStream.Write(encoding.GetBytes(_output.ToString()), 0, _output.Length);

                            var NewVsExisting = Tools.CompareMemoryStreams(originalFileMS, newDataStream);
                            if (NewVsExisting)
                            {
                                Console.WriteLine($"Skipping - Not Changed: {_config.Settings.FilePath}");
                            }
                            else
                            {
                                newDataStream.Position = 0;
                                client.Upload(newDataStream, _config.Settings.FilePath);
                                Console.WriteLine($"Uploaded: {_config.Settings.FilePath}");

                                ReloadOxidizedAsync();
                            }
                            client.Disconnect();
                        }
                    }
                }
                catch (Exception e)
                {
                    return($"Oxidized: Error with SSH Upload ({e.Message}");
                }

                // We made it past the try block so upload was successful;
                return($"Oxidized: Commit Complete");
            }
            else
            {
                return("Plugin is disabled");
            }
        }
Beispiel #21
0
        public bool DownloadLog(NotificationModel notification, string destinationFolder)
        {
            try
            {
                var pk = new PrivateKeyFile(ApplicationConstant.PrivateKeyFilePath);
                //var folder = DateTime.Now.ToString(ApplicationConstant.DatetimeFormat);
                var destination = new DirectoryInfo(destinationFolder);
                var logPath     = $"{ServerTrainConstant.DarknetPath}/{notification.LogPath}";
                var lossPath    = $"{ServerTrainConstant.DarknetPath}/{notification.LossFunctionPath}";
                var trainServer = CommonService.GetUrlApiTrainServer();
                using (var client = new ScpClient(trainServer, 22, ServerTrainConstant.Username, pk))
                {
                    client.Connect();

                    client.Download(logPath, destination);
                    client.Download(lossPath, destination);

                    client.Disconnect();
                }
            }
            catch (Exception e)
            {
                ExceptionLogging.SendErrorToText(e, nameof(this.DownloadWeight), nameof(DataSetService));
                return(false);
            }
            return(true);
        }
Beispiel #22
0
        public void Test_Scp_File_Upload_Download()
        {
            RemoveAllFiles();

            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string downloadedFileName = Path.GetTempFileName();

                this.CreateTestFile(uploadedFileName, 1);

                scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName));

                scp.Download(Path.GetFileName(uploadedFileName), new FileInfo(downloadedFileName));

                //  Calculate MD5 value
                var uploadedHash = CalculateMD5(uploadedFileName);
                var downloadedHash = CalculateMD5(downloadedFileName);

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

                scp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
        public string StartConnection()
        {
            string answer = "Połączono prawidłowo";

            Connected = false;

            try
            {
                SSHConn.Connect();
                ScpConn.Connect();

                Connected = true;
            }
            catch (Renci.SshNet.Common.SshOperationTimeoutException e)
            {
                answer = "Błąd polączenia z klastrem: " + e.Message;
            }
            catch (System.Net.Sockets.SocketException e)
            {
                answer = "Błąd polączenia z klastrem: " + e.Message;
            }
            catch (Renci.SshNet.Common.SshConnectionException e)
            {
                answer = "Błąd polączenia z klastrem: " + e.Message;
            }
            catch (Renci.SshNet.Common.SshAuthenticationException e)
            {
                answer = "Błąd autentykacji z klastrem: " + e.Message;
            }

            return(answer);
        }
        /// <summary>
        /// 开启Connect
        /// </summary>
        public void StartConnect()
        {
            try
            {
                if (m_SftpClient.IsConnected == false)
                {
                    m_SftpClient.Connect();
                }
                if (m_SshClient.IsConnected == false)
                {
                    m_SshClient.Connect();
                }
                if (m_ScpClient.IsConnected == false)
                {
                    m_ScpClient.Connect();
                }

                m_AllConnected = true;
            }
            catch { throw; }

            m_ShellStream = m_SshClient.CreateShellStream("anything", 80, 24, 800, 600, 4096);
            byte[] buffer = new byte[4096];

            m_ShellStream.DataReceived += new EventHandler <ShellDataEventArgs>(Connect_OutputDataReceived);
            m_ShellStream.ReadAsync(buffer, 0, buffer.Length);
        }
        public void Test_Scp_10MB_File_Upload_Download()
        {
            RemoveAllFiles();

            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                string uploadedFileName   = Path.GetTempFileName();
                string downloadedFileName = Path.GetTempFileName();

                this.CreateTestFile(uploadedFileName, 10);

                scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName));

                scp.Download(Path.GetFileName(uploadedFileName), new FileInfo(downloadedFileName));

                //  Calculate MD5 value
                var uploadedHash   = CalculateMD5(uploadedFileName);
                var downloadedHash = CalculateMD5(downloadedFileName);

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

                scp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
        public void Test_Scp_File_20_Parallel_Upload_Download()
        {
            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                var uploadFilenames = new string[20];
                for (int i = 0; i < uploadFilenames.Length; i++)
                {
                    uploadFilenames[i] = Path.GetTempFileName();
                    this.CreateTestFile(uploadFilenames[i], 1);
                }

                Parallel.ForEach(uploadFilenames,
                                 (filename) =>
                {
                    scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
                });

                Parallel.ForEach(uploadFilenames,
                                 (filename) =>
                {
                    scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
                });

                var result = from file in uploadFilenames
                             where
                             CalculateMD5(file) == CalculateMD5(string.Format("{0}.down", file))
                             select file;

                scp.Disconnect();

                Assert.IsTrue(result.Count() == uploadFilenames.Length);
            }
        }
Beispiel #27
0
        public void Test_Scp_Stream_Upload_Download()
        {
            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                string uploadedFileName   = Path.GetTempFileName();
                string downloadedFileName = Path.GetTempFileName();

                this.CreateTestFile(uploadedFileName, 1);

                //  Calculate has value
                using (var stream = File.OpenRead(uploadedFileName))
                {
                    scp.Upload(stream, Path.GetFileName(uploadedFileName));
                }

                using (var stream = File.OpenWrite(downloadedFileName))
                {
                    scp.Download(Path.GetFileName(uploadedFileName), stream);
                }

                //  Calculate MD5 value
                var uploadedHash   = CalculateMD5(uploadedFileName);
                var downloadedHash = CalculateMD5(downloadedFileName);

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

                scp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
Beispiel #28
0
 public Client(string host, string user, string password)
 {
     _ssh = new SshClient(host, user, password);
     _scp = new ScpClient(host, user, password);
     _ssh.Connect();
     _scp.Connect();
 }
Beispiel #29
0
        public static void mytest()
        {
            var keyFile  = new PrivateKeyFile(@"C:\Users\Administrator\.ssh\id_rsa");
            var keyFiles = new[] { keyFile };

            try
            {
                var methods = new List <AuthenticationMethod>();
                methods.Add(new PrivateKeyAuthenticationMethod(m_user, keyFiles));
                //methods.Add(new PasswordAuthenticationMethod(m_user, "chenbo"));  //加入密码

                var con = new ConnectionInfo(m_host, 22, m_user, methods.ToArray());
                using (var client = new ScpClient(con))
                {
                    String remotePath = "/data/dearMrLei/data/user_test/2017/06/16/1.pdf";
                    client.Connect();

                    // Do some stuff below
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            //C:\Users\Administrator\.ssh\id_rsa
            //var connectionInfo = new ConnectionInfo(m_host,
            //m_user,
            //new PrivateKeyAuthenticationMethod(@"C:\Users\Administrator\.ssh\id_rsa"));
        }
        /**
         * Creates SSHShell.
         *
         * @param host the host name
         * @param port the ssh port
         * @param userName the ssh user name
         * @param password the ssh password
         * @return the shell client
         */
        private SSHShell(string host, int port, string userName, string password)
        {
            var backoffTime = 30 * 1000;
            var retryCount  = 3;

            while (retryCount > 0)
            {
                try
                {
                    sshClient = new SshClient(host, port, userName, password);
                    sshClient.Connect();
                    scpClient = new ScpClient(host, port, userName, password);
                    scpClient.Connect();
                    homeDirectory = UBUNTU_HOME_DIRECTORY + userName + "/";
                    break;
                }
                catch (Exception exception)
                {
                    retryCount--;
                    if (retryCount == 0)
                    {
                        throw exception;
                    }
                }
                SdkContext.DelayProvider.Delay(backoffTime);
            }
        }
        protected void Arrange()
        {
            var random = new Random();

            _fileName          = CreateTemporaryFile(new byte[] { 1 });
            _connectionInfo    = new ConnectionInfo("host", 22, "user", new PasswordAuthenticationMethod("user", "pwd"));
            _fileInfo          = new FileInfo(_fileName);
            _path              = random.Next().ToString(CultureInfo.InvariantCulture);
            _uploadingRegister = new List <ScpUploadEventArgs>();

            _serviceFactoryMock = new Mock <IServiceFactory>(MockBehavior.Strict);
            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock <IChannelSession>(MockBehavior.Strict);
            _pipeStreamMock     = new Mock <PipeStream>(MockBehavior.Strict);

            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.CreatePipeStream()).Returns(_pipeStreamMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Open());
            _channelSessionMock.InSequence(sequence)
            .Setup(
                p => p.SendExecRequest(string.Format("scp -t \"{0}\"", _path))).Returns(false);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _pipeStreamMock.As <IDisposable>().InSequence(sequence).Setup(p => p.Dispose());

            _scpClient            = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args);
            _scpClient.Connect();
        }
Beispiel #32
0
        public Status CopyPatchToServer(string source, string destinationPath)
        {
            Status status = Status.Unknown;

            try
            {
                using (var client = new ScpClient(hostname, username, password))
                {
                    status = Status.Failed_Connect;
                    client.Connect();
                    using (var localFile = File.OpenRead(source))
                    {
                        status = Status.Failed_Transfer;
                        string destinationFile = Path.Combine(destinationPath, Path.GetFileName(source)).Replace("\\", "/");
                        client.Upload(localFile, destinationFile);
                        status = Status.Successful;
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }
            return(status);
        }
Beispiel #33
0
        protected override void Arrange()
        {
            base.Arrange();

            _scpClient            = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args);
            _scpClient.Connect();
        }
        public void Test_Scp_File_Upload_Download_Events()
        {
            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                var uploadFilenames = new string[10];

                for (int i = 0; i < uploadFilenames.Length; i++)
                {
                    uploadFilenames[i] = Path.GetTempFileName();
                    this.CreateTestFile(uploadFilenames[i], 1);
                }

                var uploadedFiles = uploadFilenames.ToDictionary((filename) => Path.GetFileName(filename), (filename) => 0L);
                var downloadedFiles = uploadFilenames.ToDictionary((filename) => string.Format("{0}.down", Path.GetFileName(filename)), (filename) => 0L);

                scp.Uploading += delegate(object sender, ScpUploadEventArgs e)
                {
                    uploadedFiles[e.Filename] = e.Uploaded;
                };

                scp.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                {
                    downloadedFiles[string.Format("{0}.down", e.Filename)] = e.Downloaded;
                };

                Parallel.ForEach(uploadFilenames,
                    (filename) =>
                    {
                        scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
                    });

                Parallel.ForEach(uploadFilenames,
                    (filename) =>
                    {
                        scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
                    });

                var result = from uf in uploadedFiles
                             from df in downloadedFiles
                             where
                                 string.Format("{0}.down", uf.Key) == df.Key
                                 && uf.Value == df.Value
                             select uf;

                scp.Disconnect();

                Assert.IsTrue(result.Count() == uploadFilenames.Length && uploadFilenames.Length == uploadedFiles.Count && uploadedFiles.Count == downloadedFiles.Count);
            }
        }
        protected void Arrange()
        {
            SetupData();
            CreateMocks();
            SetupMocks();

            _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object)
                {
                    BufferSize = (uint) _bufferSize
                };
            _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args);
            _scpClient.Connect();
        }
Beispiel #36
0
        public void Test_Scp_Directory_Upload_Download()
        {
            RemoveAllFiles();

            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                var uploadDirectory = Directory.CreateDirectory(string.Format("{0}\\{1}", Path.GetTempPath(), Path.GetRandomFileName()));
                for (int i = 0; i < 3; i++)
                {
                    var subfolder = Directory.CreateDirectory(string.Format(@"{0}\folder_{1}", uploadDirectory.FullName, i));
                    for (int j = 0; j < 5; j++)
                    {
                        this.CreateTestFile(string.Format(@"{0}\file_{1}", subfolder.FullName, j), 1);
                    }
                    this.CreateTestFile(string.Format(@"{0}\file_{1}", uploadDirectory.FullName, i), 1);
                }

                scp.Upload(uploadDirectory, "uploaded_dir");

                var downloadDirectory = Directory.CreateDirectory(string.Format("{0}\\{1}", Path.GetTempPath(), Path.GetRandomFileName()));

                scp.Download("uploaded_dir", downloadDirectory);

                var uploadedFiles = uploadDirectory.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
                var downloadFiles = downloadDirectory.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

                var result = from f1 in uploadedFiles
                             from f2 in downloadFiles
                             where
                                f1.FullName.Substring(uploadDirectory.FullName.Length) == f2.FullName.Substring(downloadDirectory.FullName.Length)
                                && CalculateMD5(f1.FullName) == CalculateMD5(f2.FullName)
                             select f1;

                var counter = result.Count();

                scp.Disconnect();

                Assert.IsTrue(counter == uploadedFiles.Length && uploadedFiles.Length == downloadFiles.Length);
            }
        }
                private void StartTransfer(SSHTransferProtocol Protocol)
                {
                    if (AllFieldsSet() == false)
                    {
                        Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg,
                                                            Language.strPleaseFillAllFields);
                        return;
                    }

                    if (File.Exists(this.txtLocalFile.Text) == false)
                    {
                        Runtime.MessageCollector.AddMessage(Messages.MessageClass.WarningMsg,
                                                            Language.strLocalFileDoesNotExist);
                        return;
                    }

                    try
                    {
                        if (Protocol == SSHTransferProtocol.SCP)
                        {
                            var ssh = new ScpClient(txtHost.Text, int.Parse(this.txtPort.Text), txtUser.Text, txtPassword.Text);
                            ssh.Uploading+=(sender, e) => SetProgressStatus(e.Uploaded, e.Size);
                            DisableButtons();
                            ssh.Connect();
                            ssh.Upload(new FileStream(txtLocalFile.Text,FileMode.Open), txtRemoteFile.Text);
                        }
                        else if (Protocol == SSHTransferProtocol.SFTP)
                        {
                            var ssh = new SftpClient(txtHost.Text, int.Parse(txtPort.Text),txtUser.Text, txtPassword.Text);
                            var s = new FileStream(txtLocalFile.Text, FileMode.Open);
                            ssh.Connect();
                            var i = ssh.BeginUploadFile(s, txtRemoteFile.Text) as SftpUploadAsyncResult;
                            ThreadPool.QueueUserWorkItem(state =>
                            {
                                while (!i.IsCompleted)
                                {
                                    SetProgressStatus((long)i.UploadedBytes, s.Length);
                                }
                                MessageBox.Show(Language.SSHTransfer_StartTransfer_Upload_completed_);
                                EnableButtons();
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg,
                                                            Language.strSSHTransferFailed + Constants.vbNewLine +
                                                            ex.Message);
                        EnableButtons();
                    }
                }
Beispiel #38
0
        public void Test_Scp_10MB_Stream_Upload_Download()
        {
            RemoveAllFiles();

            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string downloadedFileName = Path.GetTempFileName();

                this.CreateTestFile(uploadedFileName, 10);

                //  Calculate has value
                using (var stream = File.OpenRead(uploadedFileName))
                {
                    scp.Upload(stream, Path.GetFileName(uploadedFileName));
                }

                using (var stream = File.OpenWrite(downloadedFileName))
                {
                    scp.Download(Path.GetFileName(uploadedFileName), stream);
                }

                //  Calculate MD5 value
                var uploadedHash = CalculateMD5(uploadedFileName);
                var downloadedHash = CalculateMD5(downloadedFileName);

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

                scp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
        protected void Arrange()
        {
            var random = new Random();
            _bufferSize = random.Next(5, 15);
            _fileSize = _bufferSize + 2; //force uploading 2 chunks
            _fileContent = CreateContent(_fileSize);
            _fileName = CreateTemporaryFile(_fileContent);
            _connectionInfo = new ConnectionInfo("host", 22, "user", new PasswordAuthenticationMethod("user", "pwd"));
            _fileInfo = new FileInfo(_fileName);
            _path = random.Next().ToString(CultureInfo.InvariantCulture);
            _uploadingRegister = new List<ScpUploadEventArgs>();

            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _pipeStreamMock = new Mock<PipeStream>(MockBehavior.Strict);

            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.CreatePipeStream()).Returns(_pipeStreamMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Open());
            _channelSessionMock.InSequence(sequence)
                .Setup(
                    p => p.SendExecRequest(string.Format("scp -t \"{0}\"", _path))).Returns(true);
            for (var i = 0; i < random.Next(1, 3); i++)
                _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(-1);
            _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0);
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny<byte[]>()));
            for (var i = 0; i < random.Next(1, 3); i++)
                _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(-1);
            _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0);
            _channelSessionMock.InSequence(sequence)
                .Setup(p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(CreateData(
                                                                            string.Format("C0644 {0} {1}\n",
                                                                                          _fileInfo.Length,
                                                                                           Path.GetFileName(_fileName)
                                                                                         )
                                                                                     )))));
            for (var i = 0; i < random.Next(1, 3); i++)
                _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(-1);
            _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0);
#if TUNING
            _channelSessionMock.InSequence(sequence)
                .Setup(
                    p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(_fileContent.Take(_bufferSize))), 0, _bufferSize));
            _channelSessionMock.InSequence(sequence)
                .Setup(
                    p => p.SendData(It.Is<byte[]>(b => b.Take(0, _fileContent.Length - _bufferSize).SequenceEqual(_fileContent.Take(_bufferSize, _fileContent.Length - _bufferSize))), 0, _fileContent.Length - _bufferSize));
#else
            _channelSessionMock.InSequence(sequence)
                .Setup(
                    p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(_fileContent.Take(_bufferSize)))));
            _channelSessionMock.InSequence(sequence)
                .Setup(
                    p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(_fileContent.Skip(_bufferSize)))));
#endif
            _channelSessionMock.InSequence(sequence)
                .Setup(
                    p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(new byte[] { 0 }))));
            for (var i = 0; i < random.Next(1, 3); i++)
                _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(-1);
            _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Close());
            _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _pipeStreamMock.As<IDisposable>().InSequence(sequence).Setup(p => p.Dispose());

            _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object)
                {
                    BufferSize = (uint) _bufferSize
                };
            _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args);
            _scpClient.Connect();
        }