public Upload ( |
||
directoryInfo | The directory info. | |
path | string | The path. |
Résultat | void |
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> /// 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; }
/// <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; }
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(); } }
private void UploadFile(Stream input, string path) { if (_sftpClient != null) { _sftpClient.UploadFile(input, path); } else { _scpClient.Upload(input, _scpDestinationDirectory + "/" + path); } }
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"); } }
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 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; }
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) { 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(); // Print progess of download. 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)); if (e.Size != 0) { progressRecord.PercentComplete = Convert.ToInt32((e.Uploaded * 100) / e.Size); Host.UI.WriteProgress(1, progressRecord); } }; WriteVerbose("Connection succesfull"); var localfullPath = Path.GetFullPath(_localfile); if (File.Exists(localfullPath)) { WriteVerbose("Uploading " + localfullPath); var fil = new FileInfo(@localfullPath); client.Upload(fil, _remotefile); client.Disconnect(); } else { throw new FileNotFoundException("File to upload " + localfullPath + " was not found."); } } //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(); WriteVerbose("Connection succesfull"); // Print progess of download. 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)); if (e.Size != 0) { progressRecord.PercentComplete = Convert.ToInt32((e.Uploaded * 100) / e.Size); Host.UI.WriteProgress(1, progressRecord); } }; string localfullPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localfile); if (File.Exists(localfullPath)) { WriteVerbose("Uploading " + localfullPath); var fil = new FileInfo(@localfullPath); client.Upload(fil, _remotefile); client.Disconnect(); } else { throw new FileNotFoundException("File to upload " + localfullPath + " was not found."); } } }// file exist else { throw new FileNotFoundException("Key file " + fullPath + " was not found."); } } } // End process record
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(); }
/// <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; }
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 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(); } }
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"); } }
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() { 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 upload. Client.Uploading += delegate(object sender, ScpUploadEventArgs e) { var progressRecord = new ProgressRecord(1, "Uploading " + Path.GetDirectoryName(remotefolder), String.Format("{0} Bytes Uploaded of {1}", e.Uploaded, e.Size)); progressRecord.PercentComplete = Convert.ToInt32((e.Uploaded * 100) / e.Size); this.Host.UI.WriteProgress(1, progressRecord); }; var localfullPath = Path.GetFullPath(localfolder); if (Directory.Exists(localfullPath)) { WriteVerbose("Uploading " + remotefolder); DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath); Client.Upload(dirinfo, remotefolder); } else { throw new System.IO.DirectoryNotFoundException("Directory " + localfullPath + " was not found."); } 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 upload. Client.Uploading += delegate(object sender, ScpUploadEventArgs e) { var progressRecord = new ProgressRecord(1, "Uploading " + Path.GetDirectoryName(remotefolder), String.Format("{0} Bytes Uploaded of {1}", e.Uploaded, e.Size)); progressRecord.PercentComplete = Convert.ToInt32((e.Uploaded * 100) / e.Size); this.Host.UI.WriteProgress(1, progressRecord); }; var localfullPath = Path.GetFullPath(localfolder); if (Directory.Exists(localfullPath)) { WriteVerbose("Uploading " + remotefolder); DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath); Client.Upload(dirinfo, remotefolder); } else { throw new System.IO.DirectoryNotFoundException("Directory " + localfullPath + " was not found."); } Client.Disconnect(); } catch (Exception ex) { throw ex; } } }// file exist else { throw new System.IO.FileNotFoundException("Key file " + fullPath + " was not found."); } } }
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() { 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(); } } }