public SftpUploader(AppConfig conf) { this.config = conf; if (config.sftpEnabled) { AuthenticationMethod[] auths = new AuthenticationMethod[1]; if (String.IsNullOrWhiteSpace(config.sftpPrivateKeyPath)) { auths[0] = new PasswordAuthenticationMethod(config.sftpUsername, Utils.GetBytes(config.sftpPassword)); } else { try { PrivateKeyFile pkf = null; if (string.IsNullOrEmpty(config.sftpPassword)) { pkf = new PrivateKeyFile(config.sftpPrivateKeyPath); } else { pkf = new PrivateKeyFile(config.sftpPrivateKeyPath, config.sftpPassword); } auths[0] = new PrivateKeyAuthenticationMethod(config.sftpUsername, pkf); } catch (IOException) { Log.Error("Unable to read private key file: " + config.sftpPrivateKeyPath); return; } } connInfo = new ConnectionInfo(config.sftpRemoteServer, config.sftpUsername, auths); } }
public override ProcessOutput ExecuteCcm(string args, int timeout = 90000, bool throwOnProcessError = true) { var executable = GetExecutable(ref args); Trace.TraceInformation(executable + " " + args); var output = new ProcessOutput(); if (_sshClient == null) { Trace.TraceInformation("Connecting ssh client..."); var kauth = new KeyboardInteractiveAuthenticationMethod(_user); var pauth = new PasswordAuthenticationMethod(_user, _password); var connectionInfo = new ConnectionInfo(_ip, _port, _user, kauth, pauth); kauth.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e) { foreach (var prompt in e.Prompts) { if (prompt.Request.ToLowerInvariant().StartsWith("password")) { prompt.Response = _password; } } }; if (!string.IsNullOrEmpty(_privateKeyFilePath)) { var privateKeyAuth = new PrivateKeyAuthenticationMethod(_user, new PrivateKeyFile[] { new PrivateKeyFile(_privateKeyFilePath) }); connectionInfo = new ConnectionInfo(_ip, _port, _user, privateKeyAuth); } _sshClient = new SshClient(connectionInfo); } if (!_sshClient.IsConnected) _sshClient.Connect(); var result = _sshClient.RunCommand(string.Format(@"{0} {1}", executable, args)); output.ExitCode = result.ExitStatus; if (result.Error != null) { output.OutputText.Append(result.Error); } else { output.OutputText.Append(result.Result); } if (throwOnProcessError) { ValidateOutput(output); } return output; }
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(); } }
/// <summary> /// Upload Files. /// </summary> /// <returns></returns> public Boolean Put() { Boolean ok = false; // Choose Authentication Method AuthenticationMethod authenticationMethod; if (PrivateKeyPath != null && PrivateKeyPath.Trim().Length > 0) { authenticationMethod = new PrivateKeyAuthenticationMethod(UserName, new PrivateKeyFile(PrivateKeyPath, PassPhrase)); } else { authenticationMethod = new PasswordAuthenticationMethod(UserName, Password); } // Get Connection Info ConnectionInfo connectionInfo; if (Port > 0) { if (Proxy != null && Proxy.Host != null && Proxy.Host.Length > 0) { connectionInfo = new ConnectionInfo(Host, Port, UserName, (ProxyTypes)Enum.Parse(typeof(ProxyTypes), Proxy.Type.ToString()), Proxy.Host, Proxy.Port, Proxy.UserName, Proxy.Password, authenticationMethod); } else { connectionInfo = new ConnectionInfo(Host, Port, UserName, authenticationMethod); } } else { connectionInfo = new ConnectionInfo(Host, UserName, authenticationMethod); } // Uploads Boolean fail = false; using (SftpClient sftp = new SftpClient(connectionInfo)) { // Connect try { sftp.Connect(); } catch (Exception xcp) { Logger.Log($"SftpClient.Connect failed:{Environment.NewLine}{ToString()}", xcp, EventLogEntryType.Error); fail = true; } // Check Connection if (!fail && sftp.IsConnected) { // Change Directory if (Directory.Length > 0) { sftp.ChangeDirectory(Directory); } foreach (var filePath in FilePaths) { // Upload File using (FileStream file = File.OpenRead(filePath)) { try { String path = Directory.Length > 0 ? string.Format("{0}/{1}", Directory, Path.GetFileName(filePath)) : ""; Action<UInt64> del = uploadFileCallback; sftp.UploadFile(file, path, del); //uploadFileResult ok = true; } catch (System.ArgumentException xcp) { Logger.Log($"SftpClient.UploadFile failed:{Environment.NewLine}{ToString()}", xcp, EventLogEntryType.Error); throw; } catch (Exception xcp) { Logger.Log($"SftpClient.UploadFile failed:{Environment.NewLine}{ToString()}", xcp, EventLogEntryType.Error); throw; } } } // Disconnect try { sftp.Disconnect(); } catch (Exception xcp) { Logger.Log($"SftpClient.Disconnect failed:{Environment.NewLine}{ToString()}", xcp, EventLogEntryType.FailureAudit); } } } return ok && !fail; }
private void connectButton_Click(object sender, EventArgs e) { AuthenticationMethod am = null; if (noAuthRadioButton.Checked) { am = new KeyboardInteractiveAuthenticationMethod(userNameTextBox.Text); } if (passwordRadioButton.Checked) { am = new PasswordAuthenticationMethod( userNameTextBox.Text, passwordTextBox.Text); } if (keyRadioButton.Checked) { PrivateKeyFile pkf; if (passphraseTextBox.Text == "") { pkf = new PrivateKeyFile(fileNameLabel.Text); } else { pkf = new PrivateKeyFile(fileNameLabel.Text, passphraseTextBox.Text); } am = new PrivateKeyAuthenticationMethod( userNameTextBox.Text, new PrivateKeyFile[] {pkf}); } // set connection info this.connectionInfo = new ConnectionInfo( serverTextBox.Text, Int32.Parse(portTextBox.Text), userNameTextBox.Text, new AuthenticationMethod[] {am}); this.DialogResult = System.Windows.Forms.DialogResult.OK; this.Close(); }