Download() public method

Downloads the specified directory from the remote host to local directory.
is null or empty. is null.
public Download ( string directoryName, DirectoryInfo directoryInfo ) : void
directoryName string Remote host directory name.
directoryInfo System.IO.DirectoryInfo Local directory information.
return void
示例#1
0
        private bool download()
        {
            folderBrowserDialog.Description = "Choose Where To Download";
              if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
            if (listView1.SelectedItems.Count > 0) {
              try {
            listView1.Enabled = false;
            ScpClient scpClient =
                new ScpClient(this.sftpClient.ConnectionInfo);
            scpClient.Connect();
            foreach (ListViewItem lvi in listView1.SelectedItems) {
              SftpFile sf = (SftpFile)(lvi.Tag);

              if (sf.IsDirectory) {
                scpClient.Download(sf.FullName,
                    new System.IO.DirectoryInfo(folderBrowserDialog.SelectedPath).CreateSubdirectory(sf.Name));
              } else {
                scpClient.Download(sf.FullName,
                    new System.IO.FileInfo(folderBrowserDialog.SelectedPath + "\\" + sf.Name));
              }
            }
            scpClient.Disconnect();
              } catch (Exception ex) {
              } finally {
            listView1.Enabled = true;
              }
            }
              }
              return true;
        }
        public static void getData(String WAPath, String username, String password, String host)
        {
            String localPath  = "Cache.db-wal";
            String remotePath = WAPath + "/Library/Caches/net.whatsapp.WhatsApp/Cache.db-wal";
            String pwFile     = WAPath + "/Library/pw.dat";

            var scp = new Renci.SshNet.ScpClient(host, username, password);

            try
            {
                scp.Connect();
            }
            catch (Exception error)
            {
                Console.WriteLine("Coundn't connect to iPhone");
            }

            if (scp.IsConnected)
            {
                Console.WriteLine("SCP started (" + host + "). Downloading files...");
            }

            try
            {
                Stream cacheFile = File.OpenWrite(localPath);
                scp.Download(remotePath, cacheFile);
                cacheFile.Close();
            }

            catch (Exception error)
            {
                Console.WriteLine("\nCache.db-wal not found");
            }
            try
            {
                Stream filePW = File.OpenWrite("pw.dat");
                scp.Download(pwFile, filePW);
                filePW.Close();
            }
            catch (Exception error)
            {
                Console.WriteLine("\npw.dat not found\n");
            }

            scp.Disconnect();
        }
 /// <summary>
 /// Copy a file from the remote to the local machine
 /// </summary>
 /// <param name="p1"></param>
 /// <param name="p2"></param>
 public FileInfo CopyToLocal(string remoteFileName, string localFileName)
 {
     var scp = new ScpClient(_host, _username, Passwords.FetchPassword(_host, _username));
     scp.Connect();
     var lf = new FileInfo(localFileName);
     scp.Download(remoteFileName, lf);
     return lf;
 }
 private void DownloadFile(string path, Stream output)
 {
     if (_sftpClient != null)
     {
         _sftpClient.DownloadFile(path, output);
     }
     else
     {
         _scpClient.Download(_scpDestinationDirectory + "/" + path, output);
     }
 }
示例#5
0
        public void Download(string file, string host)
        {
            try
            {
                string fileName = "./" +  Path.GetFileName(file);

                using (ScpClient c = new ScpClient(host,m_userName,m_userPassword))
                {
                    Log.DebugFormat("Downloading {0} ,from: {1}", file, host);
                    c.Connect();
                    c.Download(file, new FileInfo(fileName));
                    ExitStatus = 0;
                    c.Disconnect();
                }
                Log.Debug("Reading file...");
                Result = File.ReadAllText(fileName);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Failed to download:{0} from: {1} because: {2}", file, host, ex);
                ExitStatus = -1;
            }
        }
示例#6
0
        protected override void ProcessRecord()
        {
            if (keyfile.Equals(""))
            {
                foreach (var computer in computername)
                {
                    #region AuthUserPass
                    //###########################################
                    //### Connect using Username and Password ###
                    //###########################################

                    ConnectionInfo connectInfo;
                    KeyboardInteractiveAuthenticationMethod KIconnectInfo;
                    if (proxyserver != "")
                    {
                        #region Proxy
                        // Set the proper proxy type
                        var ptype = Renci.SshNet.ProxyTypes.Http;
                        WriteVerbose("A Proxy Server has been specified");
                        switch (proxytype)
                        {
                            case "HTTP":
                                ptype = Renci.SshNet.ProxyTypes.Http;
                                break;
                            case "Socks4":
                                ptype = Renci.SshNet.ProxyTypes.Socks4;
                                break;
                            case "Socks5":
                                ptype = Renci.SshNet.ProxyTypes.Socks5;
                                break;
                        }

                        KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            port,
                            credential.GetNetworkCredential().UserName,
                            ptype,
                            proxyserver,
                            proxyport,
                            proxycredential.GetNetworkCredential().UserName,
                            proxycredential.GetNetworkCredential().Password,
                            KIconnectInfo,
                            PassconnectInfo);

                        #endregion
                    } // Proxy Server
                    else
                    {
                        #region No Proxy
                        WriteVerbose("Using Username and Password authentication for connection.");
                        // Connection info for Keyboard Interactive
                        KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        connectInfo = new Renci.SshNet.ConnectionInfo(computer, credential.GetNetworkCredential().UserName,
                                    PassconnectInfo,
                                    KIconnectInfo);

                        #endregion
                    }// No Proxy

                    // Event Handler for interactive Authentication
                    KIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = credential.GetNetworkCredential().Password;
                        }
                    };
                    try
                    {
                        //Ceate instance of SCP Client with connection info
                        var Client = new ScpClient(connectInfo);

                        // Handle host key
                        Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                        {
                            var sb = new StringBuilder();
                            foreach (var b in e.FingerPrint)
                            {
                                sb.AppendFormat("{0:x}:", b);
                            }
                            string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                            //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                            if (SSHHostKeys.ContainsKey(computer))
                            {
                                if (SSHHostKeys[computer] == FingerPrint)
                                {
                                    //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                }
                            }
                            else
                            {
                                Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                choices.Add(new ChoiceDescription("Y"));
                                choices.Add(new ChoiceDescription("N"));

                                int choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);

                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                    keymng.SetKey(computer, FingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        };

                        // Set the connection timeout
                        Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                        // Set the Operation Timeout
                        Client.OperationTimeout = TimeSpan.FromSeconds(operationtimeout);

                        // Connect to  host using Connection info
                        Client.Connect();
                        Client.BufferSize = 1024;

                        // Print progess of download.
                        Client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                        {
                            var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                            if (e.Size != 0)
                            {
                                progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                this.Host.UI.WriteProgress(1, progressRecord);
                            }
                        };

                        var localfullPath = Path.GetFullPath(localfolder);
                        WriteVerbose("Downloading " + remotefolder);
                        DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath);
                        Client.Download(remotefolder, dirinfo);
                        Client.Disconnect();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                } //end foreach computer
                    #endregion
            } //Use/Password Auth
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(keyfile);

                if (File.Exists(fullPath))
                {
                    foreach (var computer in computername)
                    {
                        PrivateKeyConnectionInfo connectionInfo;
                        if (proxyserver != "")
                        {
                            // Set the proper proxy type
                            var ptype = Renci.SshNet.ProxyTypes.Http;
                            WriteVerbose("A Proxy Server has been specified");
                            switch (proxytype)
                            {
                                case "HTTP":
                                    ptype = Renci.SshNet.ProxyTypes.Http;
                                    break;
                                case "Socks4":
                                    ptype = Renci.SshNet.ProxyTypes.Socks4;
                                    break;
                                case "Socks5":
                                    ptype = Renci.SshNet.ProxyTypes.Socks5;
                                    break;
                            }

                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);

                                if (proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        proxycredential.GetNetworkCredential().UserName,
                                        proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                        }
                        else
                        {

                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                        }

                        try
                        {
                            //Ceate instance of SCP Client with connection info
                            var Client = new ScpClient(connectionInfo);

                            // Handle host key
                            Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                            {
                                var sb = new StringBuilder();
                                foreach (var b in e.FingerPrint)
                                {
                                    sb.AppendFormat("{0:x}:", b);
                                }
                                string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                                //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                                if (SSHHostKeys.ContainsKey(computer))
                                {
                                    if (SSHHostKeys[computer] == FingerPrint)
                                    {
                                        //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                    }
                                }
                                else
                                {
                                    Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                    choices.Add(new ChoiceDescription("Y"));
                                    choices.Add(new ChoiceDescription("N"));

                                    int choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);

                                    if (choice == 0)
                                    {
                                        var keymng = new TrustedKeyMng();
                                        //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                        keymng.SetKey(computer, FingerPrint);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        e.CanTrust = false;
                                    }
                                }
                            };

                            // Set the connection timeout
                            Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                            // Set the Operation Timeout
                            Client.OperationTimeout = TimeSpan.FromSeconds(operationtimeout);

                            // Connect to  host using Connection info
                            Client.Connect();

                            Client.BufferSize = 1024;

                            // Print progess of download.
                            Client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                            {
                                var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                                if (e.Size != 0)
                                {
                                    progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                    this.Host.UI.WriteProgress(1, progressRecord);
                                }
                            };

                            var localfullPath = Path.GetFullPath(localfolder);
                            WriteVerbose("Downloading " + remotefolder);
                            DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath);
                            Client.Download(remotefolder, dirinfo);
                            Client.Disconnect();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }

                }// file exist
                else
                {
                    throw new System.IO.FileNotFoundException("Key file " + fullPath + " was not found.");
                }
            }
        }
示例#7
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo;
                if (_keyfile.Equals(""))
                {
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                        _port,
                        _credential,
                        _proxyserver,
                        _proxytype,
                        _proxyport,
                        _proxycredential,
                        kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = _credential.GetNetworkCredential().Password;
                        }
                    };

                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                        _port,
                        _keyfile,
                        _credential,
                        _proxyserver,
                        _proxytype,
                        _proxyport,
                        _proxycredential);
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(connectInfo);

                // Handle host key
                var computer1 = computer;
                client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                {
                    var sb = new StringBuilder();
                    foreach (var b in e.FingerPrint)
                    {
                        sb.AppendFormat("{0:x}:", b);
                    }
                    var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                    if (_sshHostKeys.ContainsKey(computer1))
                    {
                        if (_sshHostKeys[computer1] == fingerPrint)
                        {
                            if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                            {
                                Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer);
                            }

                            e.CanTrust = true;
                        }
                        else
                        {
                            throw new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1);
                        }
                    }
                    else
                    {
                        int choice;
                        if (_acceptkey)
                        {
                            choice = 0;
                        }
                        else
                        {
                            var choices = new Collection<ChoiceDescription>
                                {
                                    new ChoiceDescription("Y"),
                                    new ChoiceDescription("N")
                                };

                            choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                        }
                        if (choice == 0)
                        {
                            var keymng = new TrustedKeyMng();
                            keymng.SetKey(computer1, fingerPrint);
                            e.CanTrust = true;
                        }
                        else
                        {
                            e.CanTrust = false;
                        }
                    }
                };
                // Set the connection timeout
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                // Connect to host using Connection info
                client.Connect();

                var counter = 0;
                // Print progess of download.
                client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                {
                    if (e.Size != 0)
                    {
                        counter ++;
                        if (counter > 900)
                        {
                            var percent = Convert.ToInt32((e.Downloaded*100)/e.Size);
                            if (percent == 100)
                            {
                                return;
                            }

                            var progressRecord = new ProgressRecord(1,
                                "Downloading " + e.Filename,
                                String.Format("{0} Bytes Downloaded of {1}",
                                e.Downloaded, e.Size)) {PercentComplete = percent};

                            Host.UI.WriteProgress(1, progressRecord);
                            counter = 0;
                        }
                    }
                };
                WriteVerbose("Connection successful");
                var localfullPath = Path.GetFullPath(_localfile);

                WriteVerbose("Downloading " + _remotefile);
                var fil = new FileInfo(@localfullPath);

                // Download the file
                client.Download(_remotefile, fil);

                client.Disconnect();
            }
        }
示例#8
0
文件: scp.cs 项目: bielawb/Posh-SSH
        protected override void ProcessRecord()
        {
            if (_keyfile.Equals(""))
            {
                foreach (var computer in _computername)
                {
                    #region AuthUserPass
                    //###########################################
                    //### Connect using Username and Password ###
                    //###########################################

                    ConnectionInfo connectInfo;
                    KeyboardInteractiveAuthenticationMethod kIconnectInfo;
                    if (_proxyserver != "")
                    {
                        #region Proxy
                        // Set the proper proxy type
                        var ptype = ProxyTypes.Http;
                        WriteVerbose("A Proxy Server has been specified");
                        switch (_proxytype)
                        {
                            case "HTTP":
                                ptype = ProxyTypes.Http;
                                break;
                            case "Socks4":
                                ptype = ProxyTypes.Socks4;
                                break;
                            case "Socks5":
                                ptype = ProxyTypes.Socks5;
                                break;
                        }

                        kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName);
                        var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            _port,
                            _credential.GetNetworkCredential().UserName,
                            ptype,
                            _proxyserver,
                            _proxyport,
                            _proxycredential.GetNetworkCredential().UserName,
                            _proxycredential.GetNetworkCredential().Password,
                            kIconnectInfo,
                            passconnectInfo);

                        #endregion
                    } // Proxy Server
                    else
                    {
                        #region No Proxy
                        WriteVerbose("Using Username and Password authentication for connection.");
                        // Connection info for Keyboard Interactive
                        kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName);
                        var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            _port,
                            _credential.GetNetworkCredential().UserName,
                            passconnectInfo,
                            kIconnectInfo);

                        #endregion
                    }// No Proxy

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = _credential.GetNetworkCredential().Password;
                        }
                    };
                    //Ceate instance of SCP Client with connection info
                    var client = new ScpClient(connectInfo);

                    // Handle host key
                    string computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {
                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        string fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                e.CanTrust = true;
                            }
                            else
                            {
                                throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1);
                            }
                        }
                        else
                        {
                            var choices = new Collection<ChoiceDescription>
                            {
                                new ChoiceDescription("Y"),
                                new ChoiceDescription("N")
                            };

                            int choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);

                            if (choice == 0)
                            {
                                var keymng = new TrustedKeyMng();
                                //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                keymng.SetKey(computer1, fingerPrint);
                                e.CanTrust = true;
                            }
                            else
                            {
                                e.CanTrust = false;
                            }
                        }
                    };

                    // Set the connection timeout
                    client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                    // Set the Operation Timeout
                    client.OperationTimeout = TimeSpan.FromSeconds(_operationtimeout);

                    // Connect to  host using Connection info
                    client.Connect();
                    client.BufferSize = 1024;

                    // Print progess of download.
                    client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                    {
                        var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                        if (e.Size != 0)
                        {
                            progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                            Host.UI.WriteProgress(1, progressRecord);
                        }
                    };
                    WriteVerbose("Connection succesfull");
                    var localfullPath = Path.GetFullPath(_localfile);

                    WriteVerbose("Downloading " + _remotefile);
                    var fil = new FileInfo(@localfullPath);

                    // Download the file
                    client.Download(_remotefile, fil);

                    client.Disconnect();
                } //end foreach computer
                    #endregion
            } //Use/Password Auth
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(_keyfile);

                if (File.Exists(fullPath))
                {
                    foreach (var computer in _computername)
                    {
                        PrivateKeyConnectionInfo connectionInfo;
                        if (_proxyserver != "")
                        {
                            // Set the proper proxy type
                            var ptype = ProxyTypes.Http;
                            WriteVerbose("A Proxy Server has been specified");
                            switch (_proxytype)
                            {
                                case "HTTP":
                                    ptype = ProxyTypes.Http;
                                    break;
                                case "Socks4":
                                    ptype = ProxyTypes.Socks4;
                                    break;
                                case "Socks5":
                                    ptype = ProxyTypes.Socks5;
                                    break;
                            }

                            if (_credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, 
                                    _port,
                                    _credential.GetNetworkCredential().UserName, 
                                    sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password);

                                if (_proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        _port,
                                        _credential.GetNetworkCredential().UserName,
                                        ptype,
                                        _proxyserver,
                                        _proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        _port,
                                        _credential.GetNetworkCredential().UserName,
                                        ptype,
                                        _proxyserver,
                                        _proxyport,
                                        _proxycredential.GetNetworkCredential().UserName,
                                        _proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                        }
                        else
                        {

                            if (_credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, 
                                    _port,
                                    _credential.GetNetworkCredential().UserName, 
                                    sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, 
                                    _port,
                                    _credential.GetNetworkCredential().UserName, 
                                    sshkey);
                            }
                        }

                        //Ceate instance of SCP Client with connection info
                        var client = new ScpClient(connectionInfo);

                        // Handle host key
                        string computer1 = computer;
                        client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                        {
                            var sb = new StringBuilder();
                            foreach (var b in e.FingerPrint)
                            {
                                sb.AppendFormat("{0:x}:", b);
                            }
                            string fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                            if (_sshHostKeys.ContainsKey(computer1))
                            {
                                if (_sshHostKeys[computer1] == fingerPrint)
                                {
                                    //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1);
                                }
                            }
                            else
                            {
                                var choices = new Collection<ChoiceDescription>
                                {
                                    new ChoiceDescription("Y"),
                                    new ChoiceDescription("N")
                                };

                                int choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);

                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();

                                    keymng.SetKey(computer1, fingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        };

                        // Set the connection timeout
                        client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                        // Set the Operation Timeout
                        client.OperationTimeout = TimeSpan.FromSeconds(_operationtimeout);

                        // Connect to  host using Connection info
                        client.Connect();

                        client.BufferSize = 1024;

                        // Print progess of download.
                        client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                        {
                            var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                            if (e.Size != 0)
                            {
                                progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                Host.UI.WriteProgress(1, progressRecord);
                            }
                        };

                        WriteVerbose("Connection succesfull");
                        var localfullPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localfile);

                        WriteVerbose("Downloading " + _remotefile);
                        var fil = new FileInfo(@localfullPath);

                        // Download the file
                        client.Download(_remotefile, fil);

                        client.Disconnect();
                    }

                }// file exist
                else
                {
                    throw new FileNotFoundException("Key file " + fullPath + " was not found.");
                }
            }

        } // End process record
示例#9
0
 public void GetTable(string host, string userName, string rootPassword)
 {
     string file = "Table.txt";
         string fileName = "./" + Path.GetFileName(file);
         using (ScpClient c = new ScpClient(host, userName, rootPassword))
         {
             c.Connect();
             c.Download(file, new FileInfo(fileName));
             c.Disconnect();
         }
 }