public void Upload(string fileToUpload,string remotePath, string host) { try { using (ScpClient c = new ScpClient(host, m_userName, m_userPassword)) { Log.DebugFormat("Uploading file: {0} to {1}", fileToUpload, host); c.Connect(); c.Upload(new FileInfo(fileToUpload), remotePath); ExitStatus = 0; c.Disconnect(); } } catch (Exception ex) { Log.ErrorFormat("Failed to upload : {0} to {1} because: {2}", fileToUpload, host, ex); ExitStatus = -1; } }
/// <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; }
/// <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; }
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; }
/// <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; }
/// <summary> /// Open a Connection to the cloudera /// </summary> private void OpenConnecion() { sshClient = new SshClient(hostname, userName, password); sshClient.Connect(); scpClient = new ScpClient(hostname, userName, password); scpClient.Connect(); }
public void UploadFile(string fullSourcePath, string fileName) { var host = ConfigurationManager.AppSettings["Host"]; var user = ConfigurationManager.AppSettings["User"]; var port = ConfigurationManager.AppSettings["Port"]; var pass = ConfigurationManager.AppSettings["Password"]; var path = ConfigurationManager.AppSettings["Path"]; var key = ConfigurationManager.AppSettings["PrivateKey"]; int p = 22; if (!string.IsNullOrEmpty(port)) p = int.Parse(port); Log.Info("Uploading '{0}' to {1}@{2}:{3}", fileName, user, host, p); AuthenticationMethod auth; if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(user)) { Log.Info("Using public key authentication with key {0}", key); auth = new PrivateKeyAuthenticationMethod(user ,new PrivateKeyFile[]{ new PrivateKeyFile(key) }); } else if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pass)){ Log.Info("Using password authentication"); auth = new PasswordAuthenticationMethod(user,pass); } else { throw new Exception("Please ensure that username, and either PrivateKey or Password setting are defined in the configuration file."); } ConnectionInfo ConnNfo = new ConnectionInfo(host, p, user, new AuthenticationMethod[]{ auth } ); string targetPath = fileName; if (!String.IsNullOrEmpty(path)) { // If the Path config setting specifies the file name, // then ignore the local file name and always upload to the same target if (!String.IsNullOrWhiteSpace(Path.GetFileName(path))) { targetPath = path; } else { targetPath = Path.Combine(path, targetPath); // To avoid path guessing by .NET, we first combine the path, then force // potential backslashes with linux slashes. // This will obviously kill any space escaping in the path, so we need to bring those back bool hadSpaceEscapes = targetPath.Contains("\\ "); targetPath = targetPath.Replace('\\', '/'); if (hadSpaceEscapes) targetPath = targetPath.Replace("/ ", "\\ "); } } using (var scp = new ScpClient(ConnNfo)) { scp.Connect(); Log.Info("Connection opened, uploading file."); scp.Upload(new FileInfo(fullSourcePath), targetPath); Log.Info("File uploaded, closing connection."); scp.Disconnect(); } }
public SCP(Target target) { _scp = new ScpClient(target.TargetServer.Host, target.TargetServer.UserInfo, target.Password); log.InfoFormat("SCP - Connecting to {0}", target.TargetServer); _scp.Connect(); _targetPath = target.TargetServer.LocalPath; if (!_targetPath.EndsWith("/")) _targetPath += "/"; }
public static void flash_px4(string firmware_file) { if (is_solo_alive) { using (SshClient client = new SshClient("10.1.1.10", 22, "root", "TjSDBkAu")) { 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"); } }
public void Connect() { if(Protocol == SSHTransferProtocol.SCP) { ScpClt = new ScpClient(Host, Port, User, Password); ScpClt.Connect(); } if (Protocol == SSHTransferProtocol.SFTP) { SftpClt = new SftpClient(Host, Port, User, Password); SftpClt.Connect(); } }
private static void ScpUpload(string host, int port, string username, string privateKeyPath, string privateKeyPassphrase, string filePath, string destinationFilePath) { ConnectionInfo connInfo = new ConnectionInfo(host, username, new AuthenticationMethod[] { new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile[] { new PrivateKeyFile(privateKeyPath, privateKeyPassphrase) }) }); using (var scp = new ScpClient(connInfo)) { scp.Connect(); scp.Upload(new FileInfo(filePath), destinationFilePath); scp.Disconnect(); ManageClipboard(filePath); } }
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(); }
private void InternalConnect(string host, int port, string username, string password, string workingDirectory) { if (_isConnected) { // Change the working directory only if we use ScpClient. if (_scpClient != null) { ChangeWorkingDirectory(workingDirectory); } return; } // Restart timer _stopWatch.Restart(); _lastElapsedMilliseconds = 0; // Start connection ... PrintTime($"Connecting to {username}@{host}:{port} ..."); _sshClient = new SshClient(host, port, username, password); _sshClient.Connect(); try { // Use SFTP for file transfers var sftpClient = new SftpClient(host, port, username, password); sftpClient.Connect(); _sftpClient = sftpClient; } catch (Exception ex) { // Use SCP if SFTP fails PrintTime($"Error: {ex.Message} Is SFTP supported for {username}@{host}:{port}? We are using SCP instead!"); _scpClient = new ScpClient(host, port, username, password); _scpClient.Connect(); } var _connectionInfo = _sshClient.ConnectionInfo; PrintTime($"Connected to {_connectionInfo.Username}@{_connectionInfo.Host}:{_connectionInfo.Port} via SSH and {(_sftpClient != null ? "SFTP" : "SCP")}"); _isConnected = true; ChangeWorkingDirectory(workingDirectory); }
public SSHConnection(string host, string username) { // Fetch the username and password. var sclist = new CredentialSet(host); var passwordInfo = sclist.Load().Where(c => c.Username == username).FirstOrDefault(); if (passwordInfo == null) { throw new ArgumentException(string.Format("Please create a generic windows credential with '{0}' as the target address, '{1}' as the username, and the password for remote SSH access to that machine.", host, username)); } // Create the connection, but do it lazy so we don't do anything if we aren't used. _client = new Lazy<SshClient>(() => { var c = new SshClient(host, username, passwordInfo.Password); c.Connect(); return c; }); // Create the scp client for copying things _scp = new Lazy<ScpClient>(() => { var c = new ScpClient(host, username, passwordInfo.Password); c.Connect(); c.ErrorOccurred += (sender, error) => _scpError = error.Exception; return c; }); // And create a shell stream. Initialize to find the prompt so we can figure out, later, when // a task has finished. _shell = new Lazy<ShellStream>(() => { var s = _client.Value.CreateShellStream("Commands", TerminalWidth, 200, 132, 80, 240 * 200); s.WaitTillPromptText(); s.WriteLine("# this initialization"); DumpTillFind(s, "# this initialization"); s.ReadLine(); // Get past the "new-line" that is at the end of the printed comment above _prompt = s.ReadRemainingText(100); Trace.WriteLine("Initialization: prompt=" + _prompt, "SSHConnection"); return s; }); }
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; } }
private void UploadTable(string hostName, string userName, string rootPassword) { using (ScpClient c = new ScpClient(hostName, userName, rootPassword)) { c.Connect(); const string remotePath = "/"; c.Upload(new FileInfo("Table.sh"), remotePath); c.Disconnect(); } }
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."); } } }
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.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 " + computer1); } e.CanTrust = true; } else { var ex = new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1); ThrowTerminatingError(new ErrorRecord( ex, "SSH fingerprint mismatch for host " + computer1, ErrorCategory.SecurityError, 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(); //client.BufferSize = 1024; var counter = 0; // Print progess of download. client.Uploading += delegate(object sender, ScpUploadEventArgs e) { if (e.Size != 0) { counter ++; if (counter > 900) { var percent = Convert.ToInt32((e.Uploaded * 100) / e.Size); if (percent == 100) { return; } var progressRecord = new ProgressRecord(1, "Uploading " + e.Filename, String.Format("{0} Bytes Uploaded of {1}", e.Uploaded, e.Size)) {PercentComplete = percent}; Host.UI.WriteProgress(1, progressRecord); counter = 0; } } }; WriteVerbose("Connection successful"); // Resolve the path even if a relative one is given. ProviderInfo provider; var pathinfo = GetResolvedProviderPathFromPSPath(_localfile, out provider); var localfullPath = pathinfo[0]; if (File.Exists(@localfullPath)) { WriteVerbose("Uploading " + localfullPath); var fil = new FileInfo(@localfullPath); var remoteFullpath = RemotePath.TrimEnd(new[] { '/' }) + "/" + fil.Name; client.Upload(fil, remoteFullpath); client.Disconnect(); } else { var ex = new FileNotFoundException("File to upload " + localfullPath + " was not found."); ThrowTerminatingError(new ErrorRecord( ex, "File to upload " + localfullPath + " was not found.", ErrorCategory.InvalidArgument, localfullPath)); } } } // End process record
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.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); // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Handle host key if (_force) { WriteWarning("Host key for " + computer + " is not being verified since Force switch is used."); } else { 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 (MyInvocation.BoundParameters.ContainsKey("Verbose")) { Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint); } if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { if (MyInvocation.BoundParameters.ContainsKey("Verbose")) { Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1); } e.CanTrust = true; } else { e.CanTrust = false; } } else { if (_errorOnUntrusted) { e.CanTrust = false; } 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; } } } }; } try { // Connect to host using Connection info client.Connect(); var _progresspreference = (ActionPreference)this.SessionState.PSVariable.GetValue("ProgressPreference"); if (_noProgress == false) { 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"); } catch (Renci.SshNet.Common.SshConnectionException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client); WriteError(erec); } catch (Renci.SshNet.Common.SshOperationTimeoutException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client); WriteError(erec); } catch (Renci.SshNet.Common.SshAuthenticationException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client); WriteError(erec); } catch (Exception e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client); WriteError(erec); } try { if (client.IsConnected) { var localfullPath = Path.GetFullPath(_localfile); WriteVerbose("Downloading " + _remotefile); var fil = new FileInfo(@localfullPath); // Download the file client.Download(_remotefile, fil); client.Disconnect(); } } catch (Exception e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationStopped, client); WriteError(erec); } } }
/// <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; }
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
public static void flash(string firmware_file, string firmware_md5, bool clean = false) { if (is_solo_alive) { using (SshClient client = new SshClient("10.1.1.10", 22, "root", "TjSDBkAu")) { client.KeepAliveInterval = TimeSpan.FromSeconds(5); client.Connect(); if (!client.IsConnected) throw new Exception("Failed to connect ssh"); var retcode = client.RunCommand("sololink_config --update-prepare sololink"); if (retcode.ExitStatus != 0) { client.RunCommand("rm -rf /log/updates && mkdir -p /log/updates"); } 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), "/log/updates/" + Path.GetFileName(firmware_file)); scpClient.Upload(new FileInfo(firmware_md5), "/log/updates/" + Path.GetFileName(firmware_md5)); } if (clean) { retcode = client.RunCommand("sololink_config --update-apply sololink --reset"); } else { retcode = client.RunCommand("sololink_config --update-apply sololink"); } if (retcode.ExitStatus != 0) { if (clean) { retcode = client.RunCommand( "touch /log/updates/UPDATE && touch /log/updates/RESETSETTINGS && shutdown -r now"); } else { retcode = client.RunCommand("touch /log/updates/UPDATE && shutdown -r now"); } } client.Disconnect(); } } else { throw new Exception("Solo is not responding to pings"); } }
public static async Task<bool> DeployFiles(IEnumerable files, string deployLocation, ConnectionUser user) { ConnectionInfo connectionInfo; switch (user) { case ConnectionUser.Admin: connectionInfo = s_adminConnectionInfo; break; case ConnectionUser.LvUser: connectionInfo = s_lvUserConnectionInfo; break; default: throw new ArgumentOutOfRangeException(nameof(user), user, null); } if (connectionInfo == null) return false; using (ScpClient scp = new ScpClient(connectionInfo)) { try { await Task.Run(() => scp.Connect()); } catch (SshOperationTimeoutException) { return false; } var settings = (SettingsPageGrid)Frc_ExtensionPackage.Instance.PublicGetDialogPage(typeof(SettingsPageGrid)); bool verbose = settings.Verbose || settings.DebugMode; foreach (FileInfo fileInfo in from string s in files where File.Exists(s) select new FileInfo(s)) { if (verbose) { OutputWriter.Instance.WriteLine($"Deploying File: {fileInfo.Name}"); } await Task.Run(() => scp.Upload(fileInfo, deployLocation)); } } return true; }
private bool tryInitConnection() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); var ip = ConfigurationManager.AppSettings["HostIP"]; var userName = ConfigurationManager.AppSettings["HostPass"]; var pass = ConfigurationManager.AppSettings["UserName"]; try { sshConn = new SshClient(ip, userName, pass); sshConn.Connect(); sshConn.Disconnect(); } catch { return false; } try { scpClient = new ScpClient(ip, userName, pass); scpClient.Connect(); scpClient.Disconnect(); } catch { return false; } try { sftpConn = new SftpClient(ip, userName, pass); sftpConn.Connect(); sftpConn.Disconnect(); return true; } catch { return false; } }
public static void dir(string indir, string outdir) { string username = @"docker"; // Setup Credentials and Server Information string dockerHost = @"192.168.119.129"; ConnectionInfo ConnNfo = new ConnectionInfo(dockerHost, 22, username, new AuthenticationMethod[]{ // Password based Authentication new PasswordAuthenticationMethod(username, @"tcuser"), // Key Based Authentication (using keys in OpenSSH Format) //new PrivateKeyAuthenticationMethod(username,new PrivateKeyFile[]{ // new PrivateKeyFile(@"..\openssh.key","passphrase") //}), } ); //string dir = System.IO.Path.GetDirectoryName(outfile); // Execute a (SHELL) Command - prepare upload directory using (var sshclient = new SshClient(ConnNfo)) { sshclient.Connect(); // using (var cmd = sshclient.CreateCommand(@"ls /etc")) using (var cmd = sshclient.CreateCommand(@"mkdir -p " + outdir + @" && chmod +rw " + outdir)) { string output = cmd.Execute(); Console.WriteLine("Command>" + cmd.CommandText); Console.WriteLine(output); Console.WriteLine(cmd.Result); Console.WriteLine("Return Value = {0}", cmd.ExitStatus); } sshclient.Disconnect(); } // Upload A File using (var scp = new ScpClient(ConnNfo)) { scp.Connect(); scp.Upload(new System.IO.DirectoryInfo(indir), outdir); scp.Disconnect(); } }
private static void CopyTheLatestSourceFiles() { string currentDirectory = Directory.GetCurrentDirectory(); IEnumerable<string> directoryInfo = Directory.GetFiles(currentDirectory, "BuildIndicatron*.*", SearchOption.AllDirectories) .Union(Directory.GetFiles(currentDirectory, "*.html", SearchOption.AllDirectories)); ConnectionInfo connectionInfo = new PasswordConnectionInfo(Host, UserName, Password); var scpClient = new ScpClient(connectionInfo); scpClient.Connect(); _log.Info(string.Format("Copy {0} files", directoryInfo.Count())); foreach (string source in directoryInfo.Where(x => !x.Contains(".Test.dll"))) { string sourceName = source.Replace(currentDirectory + "\\", ""); string remoteFileName = Path.Combine(_homePiBuildindicatronServer, sourceName.Replace("\\", "/")); _log.Info(string.Format("Upload:{0} to {1}", sourceName, remoteFileName)); scpClient.Upload(new FileInfo(source), remoteFileName); } scpClient.Disconnect(); }
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(); } }
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(); } }
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.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 if (_force) { WriteWarning("Host key is not being verified since Force switch is used."); } else { 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 (MyInvocation.BoundParameters.ContainsKey("Verbose")) { Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint); } if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { if (MyInvocation.BoundParameters.ContainsKey("Verbose")) { Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1); } e.CanTrust = true; } else { e.CanTrust = false; } } else { if (_errorOnUntrusted) { e.CanTrust = false; } 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; } } } }; } try { // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Connect to host using Connection info client.Connect(); } catch (Renci.SshNet.Common.SshConnectionException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client); WriteError(erec); } catch (Renci.SshNet.Common.SshOperationTimeoutException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client); WriteError(erec); } catch (Renci.SshNet.Common.SshAuthenticationException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client); WriteError(erec); } catch (Exception e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client); WriteError(erec); } if (client.IsConnected) { client.BufferSize = 1024; // Print progess of upload. if (!_noProgress) { client.Uploading += delegate(object sender, ScpUploadEventArgs e) { var progressRecord = new ProgressRecord(1, "Uploading " + e.Filename, String.Format("{0} Bytes Uploaded of {1}", e.Uploaded, e.Size)) { PercentComplete = Convert.ToInt32((e.Uploaded * 100) / e.Size) }; Host.UI.WriteProgress(1, progressRecord); }; } // Resolve the path even if a relative one is given. ProviderInfo provider; var pathinfo = GetResolvedProviderPathFromPSPath(_localfolder, out provider); var localfullPath = pathinfo[0]; //var localfullPath = Path.GetFullPath(_localfolder); if (Directory.Exists(localfullPath)) { try { WriteVerbose("Uploading " + _remotefolder); var dirinfo = new DirectoryInfo(@localfullPath); client.Upload(dirinfo, _remotefolder); } catch (Exception e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client); WriteError(erec); } } else { var ex = new DirectoryNotFoundException("Directory " + localfullPath + " was not found."); WriteError(new ErrorRecord(ex, "Directory " + localfullPath + " was not found.", ErrorCategory.InvalidArgument, localfullPath)); } client.Disconnect(); } } }