public static SshExec Clone(SshBase baseConnection) { var exec = new SshExec(baseConnection.Host, baseConnection.Username, baseConnection.Password); exec.Session = baseConnection.Session; return exec; }
public static void RunExample() { SshConnectionInfo input = Util.GetInput(); try { SshExec exec = new SshExec(input.Host, input.User); if(input.Pass != null) exec.Password = input.Pass; if(input.IdentityFile != null) exec.AddIdentityFile( input.IdentityFile ); Console.Write("Connecting..."); exec.Connect(); Console.WriteLine("OK"); while(true) { Console.Write("Enter a command to execute ['Enter' to cancel]: "); string command = Console.ReadLine(); if(command=="")break; string output = exec.RunCommand(command); Console.WriteLine(output); } Console.Write("Disconnecting..."); exec.Close(); Console.WriteLine("OK"); } catch(Exception e) { Console.WriteLine(e.Message); } }
private static string SshRun(string host, string command, bool ignoreErrors = false) { var ssh = new SSH.SshExec(host.Split(':')[0], User, Password); if (host.Contains(":")) { ssh.Connect(Int32.Parse(host.Split(':')[1])); } else { ssh.Connect(); } string sshOut = ""; string sshErr = ""; string sshCommand = command; int sshResult = ssh.RunCommand(sshCommand, ref sshOut, ref sshErr); ssh.Close(); if (!String.IsNullOrWhiteSpace(sshErr) && !ignoreErrors) { throw new Exception(String.Format("Ssh execution error. Command: \"{0}\". Code: {1}, StdOut: {2}, StdErr: {3}", sshCommand, sshResult, sshOut, sshErr)); } return(sshOut); }
private void button1_Click(object sender, EventArgs e) { try { string host = textBox1.Text; string user = "******"; string password = "******"; string command = textBox2.Text; SshExec shell = new SshExec(host, user); shell.Password = password; textBox3.Text = "Connecting"; shell.Connect(); textBox3.Text = "Ok"; if (command == "close") { textBox3.Text = "Disconnecting"; shell.Close(); textBox3.Text = "Ok"; } else { string output = shell.RunCommand(command); label3.Text = output; } } catch(Exception ex) { textBox3.Text = ex.Message; } }
private void cmdClose_Click(object sender, EventArgs e) { SshExec ssh = new SshExec(host, user, password); ssh.Connect(); ssh.RunCommand("/bin/bash /home/" + user + "/.cloverleaf/" + Path.GetFileName(closeScriptPath)); System.Diagnostics.Process.GetCurrentProcess().Kill(); }
public static SshExec Clone(SshBase baseConnection) { var exec = new SshExec(baseConnection.Host, baseConnection.Username, baseConnection.Password); exec.Session = baseConnection.Session; return(exec); }
// public static void Add(ESXiConnection connection) // { // connections.Add(connection); // } public static ESXiConnection Add( ESXiConnection connection, SshExec ssh) { connection.Ssh = ssh; connections.Add(connection); return connection; }
private void RunScript(string host, NodeAuth auth) { SshExec exec = new SshExec (host, auth.UserName); SetupSSH (exec, auth); exec.RunCommand (RemoteScriptPath); }
/// <summary> /// 在远程主机执行一条命令 /// </summary> /// <param name="SshConnInfo">SSH连接信息,包含主机名,用户名,密码,以及要执行的命令语句</param> public void ExecCmd( ) { string Response; SshUtil SshConnInfo = this._SshConnInfo; try { if (SshConnInfo.Host.Trim() == "") { return; } SshExec Exec = new SshExec(SshConnInfo.Host, SshConnInfo.UserName, SshConnInfo.PassWord); //Console.WriteLine("Process {0} ....", SshConnInfo.Host); try { Exec.Connect(); } catch (Exception) { //Console.WriteLine("Connect {0} error...", SshConnInfo.Host); return; } try { Response = Exec.RunCommand(SshConnInfo.Cmd); if (Response.Trim() != "") { Console.WriteLine("{0}\n{1}", SshConnInfo.Host, Response); } else { return; } } catch (Exception) { //Console.WriteLine("Run cmd on {0} error...", SshConnInfo.Host); return; } Exec.Close(); } catch (ThreadAbortException) { //Console.WriteLine("Process {0} time out...", SshConnInfo.Host); return; } catch (Exception) { //Console.WriteLine("Process {0} error...", SshConnInfo.Host); return; } }
public SystemInformation GetSystemInformationFrom(TargetInfo target) { var sshExec = new SshExec(target.GetAddress(), target.credentials.GetUserName(), target.credentials.GetPassword()); sshExec.Connect(target.GetPort()); var collectedUnixSystemInformation = SystemInformationCollector.getSysInfo(sshExec); return this.CreateSystemInformationInstance(collectedUnixSystemInformation); }
protected void RunCommand(string command, string host, NodeAuth auth) { SshExec exec = new SshExec (host, auth.UserName); SetupSSH (exec, auth); Console.WriteLine ("running command: {0} on host: {1}", command, host); Console.WriteLine (exec.RunCommand (command)); exec.Close (); }
public void Start(RemoteDevice target) { //hacky but openssh seems to ignore signals Action start = delegate { var startexec = new SshExec(target.target.ToString(), target.username, target.password); startexec.Connect(); var result = startexec.RunCommand("mono /root/FlightControl/FlightControl.exe"); startexec.Close(); }; start.Invoke(); }
public void Kill(RemoteDevice target) { //hacky but openssh seems to ignore signals Action kill = delegate { var killExec = new SshExec(target.target.ToString(), target.username, target.password); killExec.Connect(); var killcmd = @"killall mono"; var result = killExec.RunCommand(killcmd); result = killExec.RunCommand("killall FCRestarter"); killExec.Close(); }; kill.Invoke(); }
public override void Run(Node node, NodeAuth auth) { if (node == null) throw new ArgumentNullException ("node"); if (auth == null) throw new ArgumentNullException ("auth"); if (node.PublicIPs.Count < 1) throw new ArgumentException ("node", "No public IPs available on node."); string host = node.PublicIPs [0].ToString (); CopyScript (host, auth); SshExec exec = new SshExec (host, auth.UserName); }
public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction) { ConnectionManager conn = getCurrentConnectionManager(connections); List<KeyValuePair<string, string>> connParams = (List<KeyValuePair<string, string>>)conn.AcquireConnection(transaction); string host = connParams.Find(t => t.Key == "Host").Value; string username = connParams.Find(t => t.Key == "Username").Value; string password = connParams.Find(t => t.Key == "Password").Value; int port = Convert.ToInt32(connParams.Find(t => t.Key == "Port").Value); SshExec exec = new SshExec(host, username); exec.Password = password; try { string stdOut = string.Empty; string stdErr = string.Empty; exec.Connect(); StringReader sr = new StringReader(_commandText); while (true) { string s = sr.ReadLine(); if (s != null && stdErr.Trim().Length == 0) { int res = exec.RunCommand(s, ref stdOut, ref stdErr); } else { if (stdErr.Trim().Length > 0) { fireError(componentEvents, stdErr); return DTSExecResult.Failure; } break; } } } catch (Exception ex) { fireError(componentEvents, ex.Message); return DTSExecResult.Failure; } finally { exec.Close(); } return DTSExecResult.Success; }
public void Run() { try { SshConnectionInfo input = Util.GetInput(); exec = new SshExec(input.Host, input.User); if (input.Pass != null) exec.Password = input.Pass; exec.Connect(); string command = Console.ReadLine(); string output = exec.RunCommand(command); Console.WriteLine(output); exec.Close(); } catch(Exception e) { Console.WriteLine(e.Message); } }
public static void ExecuteSingleCommand(string command) { try { //create a new ssh stream SshExec ssh = new SshExec(MACHINE_IP, USER_NAME, PASSWORD); ssh.Connect(); //writing to the ssh channel var str = ssh.RunCommand(command); ssh.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } }
public override void ProcessCommand(OSAEMethod method) { try { string[] tmp = method.Parameter1.Split('/'); server = tmp[0]; username = tmp[1]; password = tmp[2]; string command = method.Parameter2; Log.Debug("Sending command: " + command + " | " + server + " | " + username + " | " + password); SshExec ssh = new SshExec(server, username, password); ssh.Connect(); string response = ssh.RunCommand(command); Log.Debug("Response: " + response); ssh.Close(); } catch (Exception ex) { Log.Error("Error Sending command", ex); } }
public void CheckJobStatus() { string stdout = ""; //string stderr = ""; bool atleastOne = false; SshShell shell = new SshShell(Consts.DEFAULT_HOST, Consts.DEFAULT_USERNAME, Consts.DEFAULT_PASSWORD); SshExec exec = new SshExec(Consts.DEFAULT_HOST, Consts.DEFAULT_USERNAME, Consts.DEFAULT_PASSWORD); Thread.Sleep(1000); string jobId; int runningJobs = 0; while (!atleastOne || runningJobs != 0) { stdout = runStatusCommand(shell, exec, "mapred job -list"); runningJobs = Int32.Parse(stdout.Split(null).ToList()[0]); if (runningJobs != 0) { atleastOne = true; jobId = stdout.Split(null).ToList().Where(line => line.Contains("job_")).First(); double map; double reduce; while (true) { stdout = runStatusCommand(shell, exec, $"mapred job -status {jobId}"); map = Double.Parse((stdout.Split('\n').Where(line => line.Contains("map()")).First().ToString()).Split(null)[2]) * 100; reduce = Double.Parse((stdout.Split('\n').Where(line => line.Contains("reduce()")).First().ToString()).Split(null)[2]) * 100; StatusModel.Instance.setProgress((int)((reduce + map) / 2), 100); StatusModel.Instance.Status = $"Map {(int)map}% - Reduce {(int)reduce}%"; if (reduce == 100) break; Thread.Sleep(500); } } } StatusModel.Instance.Status = "Finished MapReduce!"; }
public override void ProcessCommand(OSAEMethod method) { try { string[] tmp = method.Parameter1.Split('/'); server = tmp[0]; username = tmp[1]; password = tmp[2]; string command = method.Parameter2; logging.AddToLog("Sending command: " + command + " | " + server + " | " + username + " | " + password, false); SshExec ssh = new SshExec(server, username, password); ssh.Connect(); string response = ssh.RunCommand(command); logging.AddToLog("Response: " + response, false); ssh.Close(); } catch (Exception ex) { logging.AddToLog("Error Sending command - " + ex.Message + " -" + ex.InnerException, true); } }
public bool Test() { bool result = false; SshExec exec = new SshExec(host, username); // SshShell exec = new SshShell(host, username); try { exec.Password = password; if (!string.IsNullOrEmpty(pkFile)) { exec.AddIdentityFile(pkFile); } exec.Connect(); string output = exec.RunCommand(commandText); Console.WriteLine(output); result = true; } catch (Exception) { result = false; } finally { try { if (exec != null && exec.Connected) { exec.Close(); } } catch { } } return result; }
public void ProcessCommand(System.Data.DataTable table) { System.Data.DataRow row = table.Rows[0]; //process command try { string[] tmp = row["parameter_1"].ToString().Split('/'); server = tmp[0]; username = tmp[1]; password = tmp[2]; string command = row["parameter_2"].ToString(); osae.AddToLog("Sending command: " + command + " | " + server + " | " + username + " | " + password, false); SshExec ssh = new SshExec(server, username, password); ssh.Connect(); string response = ssh.RunCommand(command); osae.AddToLog("Response: " + response, false); ssh.Close(); } catch (Exception ex) { osae.AddToLog("Error Sending command - " + ex.Message + " -" + ex.InnerException, true); } }
private static string SshExec(string command, string args = "", string pilotUrl = null) { lock (_gridLock) { string pilotUrlOrEmpty = command.ToLower().StartsWith("pilot") ? @" --url '" + pilotUrl + "'" : ""; var sshExec = new SSH.SshExec(HELPER_SSH_HOST, HELPER_SSH_USER, HELPER_SSH_PASS); sshExec.Connect(); string sshOut = ""; string sshErr = ""; string sshCommand = command + " " + args + pilotUrlOrEmpty; int sshResult = sshExec.RunCommand(sshCommand, ref sshOut, ref sshErr); sshExec.Close(); sshErr = sshErr.Replace('.', ' '); // Cert creation emits many dots if (!String.IsNullOrWhiteSpace(sshErr)) { throw new Exception(String.Format("Ssh execution error. Command: \"{0}\". Code: {1}, StdOut: {2}, StdErr: {3}", sshCommand, sshResult, sshOut, sshErr)); } return(sshOut); } }
private SshExec getCommander() { //using Tamir.SharpSsh; Tamir.SharpSsh.SshExec e = new SshExec(HostName, UserName, Password); e.Connect(); return e; }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { UserPrincipal user = GetUser(username) ?? null; if (user == null) { user = new UserPrincipal(GetPrincipalContext()); //User Log on Name user.SamAccountName = username; user.SetPassword(password); user.Enabled = true; user.UserPrincipalName = username; user.GivenName = username; user.Surname = username; user.EmailAddress = email; user.UserCannotChangePassword = false; user.DisplayName = username; try { user.Save(); MembershipUser msUser = new MembershipUser("ActiveDirectoryMembershipProvider", user.SamAccountName, providerUserKey, user.EmailAddress, string.Empty, string.Empty, true, user.IsAccountLockedOut(), DateTime.MinValue, user.LastLogon ?? DateTime.Now, user.LastBadPasswordAttempt ?? DateTime.Now, user.LastPasswordSet ?? DateTime.Now, user.AccountLockoutTime ?? DateTime.Now); // Nos conectamos via SSH hacia el servidor de Zimbra SshExec exec = new SshExec("mail.dxstudio.net", "alex"); exec.Password = "******"; exec.Connect(); // Una vez conectados al servidor de Zimbra // estructuramos y armamos el comando Linux // necesario crear el MailBox string strCommand = string.Empty; strCommand = "/opt/zimbra/bin/./zmprov -a admin -p Admin1234 ca " + user.SamAccountName + "@dxstudio.net SoyUnPassword"; // Ejecutamos el comando Linux para crear el MailBox strCommand = exec.RunCommand(strCommand); // Cerreamos la Conexion SSH exec.Close(); // Enviamos Mensaje de bienvenida SenMail(user.SamAccountName); status = MembershipCreateStatus.Success; return msUser; } catch (Exception ex) { // verificamos que efectivamente no se cree el usuario var usr = GetUser(username) ?? null; if (usr != null) usr.Delete(); status = MembershipCreateStatus.UserRejected; return null; } } else { MembershipUser msUser = new MembershipUser("ActiveDirectoryMembershipProvider", user.SamAccountName, providerUserKey, user.EmailAddress, string.Empty, string.Empty, true, user.IsAccountLockedOut(), DateTime.MinValue, user.LastLogon ?? DateTime.Now, user.LastBadPasswordAttempt ?? DateTime.Now, user.LastPasswordSet ?? DateTime.Now, user.AccountLockoutTime ?? DateTime.Now); status = MembershipCreateStatus.DuplicateUserName; return msUser; } }
public override bool DeleteUser(string username, bool deleteAllRelatedData) { var usr = GetUser(username) ?? null; if (usr != null) { try { usr.Delete(); //borramos el mailbox SshExec exec = new SshExec("mail.dxstudio.net", "alex"); exec.Password = "******"; exec.Connect(); string strCommand = string.Empty; strCommand = "/opt/zimbra/bin/./zmprov -a admin -p Admin1234 da " + usr.SamAccountName + "@dxstudio.net"; // Ejecutamos el comando Linux para eliminar el MailBox strCommand = exec.RunCommand(strCommand); // Cerreamos la Conexion SSH exec.Close(); return true; } catch (Exception) { return false; } } else return false; }
public virtual List<string> GetTargetServices(SshExec exec) { string cmdOutput = exec.RunCommand("ls -l /etc/init.d/ 2>/dev/null | grep '^-..x'"); return UnixTerminalParser.GetServicesFromTerminalOutput(cmdOutput).ToList(); }
private static void OpenSshConnection() { ssh = new SshExec(host, user, password); ssh.Connect(sshPort); Console.WriteLine("Connected"); sftpBase = new Tamir.SharpSsh.Sftp(host, user, password); sftpBase.OnTransferStart += new FileTransferEvent(sftpBase_OnTransferStart); sftpBase.OnTransferEnd += new FileTransferEvent(sftpBase_OnTransferEnd); Console.WriteLine("Trying to Open Connection..."); sftpBase.Connect(sshPort); Console.WriteLine("Connected Successfully !"); }
private static string SshRun(string host, string command, bool ignoreErrors = false) { var ssh = new SSH.SshExec(host.Split(':')[0], User, Password); if (host.Contains(":")) { ssh.Connect(Int32.Parse(host.Split(':')[1])); } else { ssh.Connect(); } string sshOut = ""; string sshErr = ""; string sshCommand = command; int sshResult = ssh.RunCommand(sshCommand, ref sshOut, ref sshErr); ssh.Close(); if (!String.IsNullOrWhiteSpace(sshErr) && !ignoreErrors) throw new Exception(String.Format("Ssh execution error. Command: \"{0}\". Code: {1}, StdOut: {2}, StdErr: {3}", sshCommand, sshResult, sshOut, sshErr)); return sshOut; }
private void cmdOK_Click(object sender, EventArgs e) { String app = projectDirectory; CloverleafEnvironment.RemoteServerHost = txtHostName.Text; this.Hide(); String host = txtHostName.Text; String user = txtUsername.Text; String password = txtPassword.Text; Int32 port = FirstOpenPort(host, 60000, 65000); String zipDirectory = CloverleafEnvironment.CloverleafAppDataPath; String zipFileName = "web." + host + "." + user + "." + DateTime.Now.Ticks.ToString() + ".zip"; String zipPath = Path.Combine(zipDirectory, zipFileName); String scriptPath = Path.Combine(zipDirectory, "web." + host + "." + user + "." + DateTime.Now.Ticks.ToString() + ".sh"); String closeScriptPath = Path.Combine(zipDirectory, "web." + host + "." + user + "." + DateTime.Now.Ticks.ToString() + ".close.sh"); String pidPath = Path.GetFileNameWithoutExtension(zipFileName) + ".pid"; String remoteDirectory = Path.GetFileNameWithoutExtension(zipFileName); FastZip fz = new FastZip(); fz.CreateEmptyDirectories = true; fz.RestoreAttributesOnExtract = true; fz.RestoreDateTimeOnExtract = true; fz.CreateZip(zipPath, app, true, null); Scp scp = new Scp(host, user, password); scp.Connect(); if (scp.Connected == false) { throw new SshTransferException("Couldn't connect to host with SCP."); } scp.Mkdir("/home/" + user + "/.cloverleaf"); scp.Put(zipPath, "/home/" + user + "/.cloverleaf/" + zipFileName); File.Delete(zipPath); String ssh1ArgumentData = ""; String ssh2ArgumentData = ""; if (optXSP.Checked == true) { ssh1ArgumentData = "#! /bin/bash" + "\n" + "cd /home/" + user + "/.cloverleaf" + "\n" + "mkdir " + remoteDirectory + "\n" + "cp " + zipFileName + " " + remoteDirectory + "\n" + "cd " + remoteDirectory + "\n" + "unzip " + zipFileName + " > /dev/null \n" + "xsp2 --nonstop --port " + port.ToString() + "& \n" + "pgrep -l " + user + " -n mono > /home/" + user + "/.cloverleaf/" + pidPath; ssh2ArgumentData = "#! /bin/bash" + "\n" + "cd /home/" + user + "/.cloverleaf" + "\n" + "kill `cat " + pidPath + "`" + "\n" + "rm -rf " + Path.GetFileNameWithoutExtension(pidPath) + "*"; } File.WriteAllText(scriptPath, ssh1ArgumentData); File.WriteAllText(closeScriptPath, ssh2ArgumentData); if (scp.Connected == false) { throw new SshTransferException("Couldn't connect to host with SCP."); } scp.Put(scriptPath, "/home/" + user + "/.cloverleaf/" + Path.GetFileName(scriptPath)); scp.Put(closeScriptPath, "/home/" + user + "/.cloverleaf/" + Path.GetFileName(closeScriptPath)); String stdOut = ""; String stdErr = ""; SshExec ssh = new SshExec(host, user, password); ssh.Connect(); ssh.RunCommand("/bin/bash /home/" + user + "/.cloverleaf/" + Path.GetFileName(scriptPath), ref stdOut, ref stdErr); (new RemoteWebServerCloser(Path.GetFileName(closeScriptPath), host, user, password)).Show(); ProcessStartInfo wwwProcInfo = new ProcessStartInfo(); wwwProcInfo.FileName = "http://" + host + ":" + port.ToString(); wwwProcInfo.UseShellExecute = true; Process wwwProc = new Process(); wwwProc.StartInfo = wwwProcInfo; wwwProc.Start(); }
public SSHManager(string host, string username, string password) { _shell = new SshShell(host, username, password); _exec = new SshExec(host, username, password); _sshCp = new Scp(host, username, password); }
private string runStatusCommand(SshShell shell, SshExec exec, string command) { string stdout = ""; string stderr = ""; shell.Connect(); shell.RedirectToConsole(); exec.Connect(); int ret = exec.RunCommand(command, ref stdout, ref stderr); exec.Close(); shell.Close(); return stdout; }
private static string SshExec(string command, string args = "", string pilotUrl = null) { lock (_gridLock) { string pilotUrlOrEmpty = command.ToLower().StartsWith("pilot") ? @" --url '" + pilotUrl + "'" : ""; var sshExec = new SSH.SshExec(HELPER_SSH_HOST, HELPER_SSH_USER, HELPER_SSH_PASS); sshExec.Connect(); string sshOut = ""; string sshErr = ""; string sshCommand = command + " " + args + pilotUrlOrEmpty; int sshResult = sshExec.RunCommand(sshCommand, ref sshOut, ref sshErr); sshExec.Close(); sshErr = sshErr.Replace('.', ' '); // Cert creation emits many dots if (!String.IsNullOrWhiteSpace(sshErr)) throw new Exception(String.Format("Ssh execution error. Command: \"{0}\". Code: {1}, StdOut: {2}, StdErr: {3}", sshCommand, sshResult, sshOut, sshErr)); return sshOut; } }