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(); }
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; } }
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 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(); }
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; } }
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 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 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; }
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); } }
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 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; }
public static SysInfo getSysInfo(SshExec exec) { string arch; SysInfo mySysInfo = new SysInfo(); char[] separators = { ' ', '\t' }; string output = exec.RunCommand("uname -a"); string[] unameparts = output.Split(separators, StringSplitOptions.RemoveEmptyEntries); mySysInfo.OS = unameparts[0]; mySysInfo.Hostname = unameparts[1]; mySysInfo.Interfaces = new List<InterfaceState>(); switch (mySysInfo.OS) { case "Linux": mySysInfo.OSVersion = unameparts[2]; arch = exec.RunCommand("uname -m").Trim(); getInterfacesLinux(exec, mySysInfo); break; case "Darwin": mySysInfo.OSVersion = unameparts[2]; arch = exec.RunCommand("uname -m").Trim(); getInterfacesMacOSX(exec, mySysInfo); break; case "FreeBSD": mySysInfo.OSVersion = unameparts[2]; arch = exec.RunCommand("uname -m").Trim(); getInterfacesBSD(exec, mySysInfo); break; case "SunOS": mySysInfo.OSVersion = unameparts[2]; arch = exec.RunCommand("uname -p").Trim(); getInterfacesSolaris(exec, mySysInfo); break; case "AIX": mySysInfo.OSVersion = unameparts[3] + "." + unameparts[2]; arch = exec.RunCommand("uname -p").Trim(); getInterfacesAIX(exec, mySysInfo); break; default: throw new Exception(String.Format("Unsupported OS {0}", mySysInfo.OS)); } switch (arch) { case "i386": case "i486": case "i586": case "i686": mySysInfo.Architecture = "INTEL32"; break; case "x86_64": mySysInfo.Architecture = "INTEL64"; break; case "sparc": mySysInfo.Architecture = "SPARC"; break; case "mips": mySysInfo.Architecture = "MIPS"; break; case "ppc": case "powerpc": mySysInfo.Architecture = "POWERPC32"; break; case "ppc64": mySysInfo.Architecture = "POWERPC64"; break; case "alpha": mySysInfo.Architecture = "ALPHA32"; break; case "alpha64": mySysInfo.Architecture = "ALPHA64"; break; default: mySysInfo.Architecture = "UNKNOWN"; break; } return mySysInfo; }
// This should only be run for sequencing jobs, i.e. those requiring PhRed validation. // run phred private void RunPhred(int barcode) { // list of commands to execute // cp -R /mnt/cgfdata/raw/{barcode} /home/caesdev/raw // mkdir /home/caesdev/output/{barcode} // /opt/pkg/genome/bin/phred -id /home/caesdev/raw/{barcode} -qd /home/caesdev/output/{barcode} // cp -R /home/caesdev/output/{barcode} /mnt/cgfdata/output string output = null, error = null; var ssh = new SshExec(PhredServer, PhredUsername, PhredPassword); ssh.Connect(); try { // copy in data //ssh.RunCommand(string.Format(@"cp -R /mnt/cgfdata/raw/{0} /home/{1}/raw", barcode, PhredUsername)); ssh.RunCommand(string.Format(@"cp -R /mnt/cgfdata/Backup/raw/{0} /home/{1}/raw", barcode, PhredUsername)); ssh.RunCommand(string.Format(@"mkdir /home/{0}/output/{1}", PhredUsername, barcode)); // execute ssh.RunCommand(string.Format(@"/opt/pkg/genome/bin/phred -id /home/{0}/raw/{1} -qd /home/{0}/output/{1}", PhredUsername, barcode), ref output, ref error); if (!string.IsNullOrEmpty(error)) { throw new Exception(error); } // clean up //ssh.RunCommand(string.Format(@"mv /home/{0}/output/{1} /mnt/cgfdata/output", PhredUsername, barcode)); ssh.RunCommand(string.Format(@"mv /home/{0}/output/{1} /mnt/cgfdata/Backup/output", PhredUsername, barcode)); ssh.RunCommand(string.Format(@"rm /home/{0}/raw/{1}/*", PhredUsername, barcode)); ssh.RunCommand(string.Format(@"rmdir /home/{0}/raw/{1}", PhredUsername, barcode)); } catch { // automatic cleanup ssh.RunCommand(string.Format(@"rm /home/{0}/output/{1}/*", PhredUsername, barcode)); ssh.RunCommand(string.Format(@"rmdir /home/{0}/output/{1}", PhredUsername, barcode)); ssh.RunCommand(string.Format(@"rm /home/{0}/raw/{1}/*", PhredUsername, barcode)); ssh.RunCommand(string.Format(@"rmdir /home/{0}/raw/{1}", PhredUsername, barcode)); } ssh.Close(); }
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 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; } }
private static void getInterfacesLinux(SshExec exec, SysInfo mySysInfo) { uint ifIndex = 0; InterfaceState curif = null; char[] lineseps = { '\r', '\n' }; char[] fieldseps = { ' ', '\t' }; string output = exec.RunCommand("/sbin/ip addr show"); string[] lines = output.Split(lineseps, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { if ((line[0] >= '0') && (line[0] <= '9')) { if (curif != null) mySysInfo.Interfaces.Add(curif); curif = new InterfaceState(); curif.InetAddr = new List<InterfaceState.IPInfo>(); curif.Index = ifIndex++; string[] ifields = line.Split(fieldseps, StringSplitOptions.RemoveEmptyEntries); curif.Name = ifields[1].Replace(":", ""); } else { string[] pfields = line.Split(fieldseps, StringSplitOptions.RemoveEmptyEntries); if (pfields[0].StartsWith("link/")) { string itype = pfields[0].Remove(0, 5); switch (itype) { case "ether": curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_ETHERNET; curif.IsPhysical = true; break; case "loopback": curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_LOOPBACK; curif.IsPhysical = false; break; case "ppp": curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_PPP; curif.IsPhysical = false; break; case "fddi": curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_FDDI; curif.IsPhysical = true; break; case "tr": curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_TOKENRING; curif.IsPhysical = true; break; case "slip": case "cslip": case "slip6": case "cslip6": curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_SLIP; curif.IsPhysical = false; break; default: curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_OTHER; break; } curif.HWAddr = pfields[1]; } else if (pfields[0] == "inet") { char[] sepslash = { '/' }; string[] addrAndMask = pfields[1].Split(sepslash); InterfaceState.IPInfo curip; curip.IPAddr = addrAndMask[0]; if (addrAndMask[1].Contains(".")) curip.IPMask = addrAndMask[1]; else { uint hostbits = uint.Parse(addrAndMask[1]); if (hostbits <= 8) curip.IPMask = String.Format("{0}.0.0.0", (0xFF00 >> (int)hostbits) & 0x00FF); else if (hostbits <= 16) curip.IPMask = String.Format("255.{0}.0.0", (0xFF00 >> (int)(hostbits - 8)) & 0x00FF); else if (hostbits <= 24) curip.IPMask = String.Format("255.255.{0}.0", (0xFF00 >> (int)(hostbits - 16)) & 0x00FF); else if (hostbits <= 32) curip.IPMask = String.Format("255.255.{0}.0", (0xFF00 >> (int)(hostbits - 24)) & 0x00FF); else throw new InvalidOperationException(String.Format("Netmask bits in '{0}' ({1}) outside acceptable range", curif.Name, hostbits)); } curip.IPBcast = TokenFollowing(pfields, "brd"); curip.AddrType = InterfaceState.stateAddrType.MIB_IPADDR_PRIMARY; curif.InetAddr.Add(curip); } } } if (curif != null) mySysInfo.Interfaces.Add(curif); }
private static void getInterfacesSolaris(SshExec exec, SysInfo mySysInfo) { uint ifIndex = 0; InterfaceState curif = null; char[] lineseps = { '\r', '\n' }; char[] fieldseps = { ' ', '\t' }; string output = exec.RunCommand("/sbin/ifconfig -a"); string[] lines = output.Split(lineseps, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { if (!char.IsWhiteSpace(line[0])) { if (curif != null) { getMACAIX(exec, curif); mySysInfo.Interfaces.Add(curif); } curif = new InterfaceState(); curif.InetAddr = new List<InterfaceState.IPInfo>(); curif.Index = ifIndex++; string[] ifields = line.Split(fieldseps, StringSplitOptions.RemoveEmptyEntries); curif.Name = ifields[0].Replace(":", ""); string iflags = ifields[1].Replace("<", ",").Replace(">", ","); if (iflags.Contains(",LOOPBACK,")) { curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_LOOPBACK; curif.IsPhysical = false; } else if (iflags.Contains(",VIRTUAL,")) { curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_OTHER; curif.IsPhysical = false; } else { curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_OTHER; curif.IsPhysical = true; } } else { string[] pfields = line.Split(fieldseps, StringSplitOptions.RemoveEmptyEntries); if (pfields[0] == "ether") { curif.Type = InterfaceState.stateInterfaceType.MIB_IF_TYPE_ETHERNET; string[] macParts = pfields[1].Split(':'); if (macParts.Length == 6) { for (int i = 0; i < macParts.Length; i++) { if (macParts[i].Length == 1) macParts[i] = "0" + macParts[i]; } curif.HWAddr = String.Join(":", macParts); } } else if (pfields[0] == "inet") { InterfaceState.IPInfo curip = new InterfaceState.IPInfo(); curip.IPAddr = pfields[1]; if ((pfields.Length > 5) && (pfields[4] == "broadcast")) curip.IPBcast = pfields[5]; else curip.IPBcast = ""; if ((pfields.Length > 3) && (pfields[2] == "netmask")) { if (pfields[3].Contains(".")) curip.IPMask = pfields[3]; else { if (pfields[3].StartsWith("0x")) pfields[3] = pfields[3].Substring(2); UInt32 masknum = Convert.ToUInt32(pfields[3], 16); curip.IPMask = String.Format("{0}.{1}.{2}.{3}", masknum >> 24, (masknum >> 16) & 0x00FF, (masknum >> 8) & 0x00FF, masknum & 0x00FF); } } else curip.IPMask = ""; curip.AddrType = InterfaceState.stateAddrType.MIB_IPADDR_PRIMARY; curif.InetAddr.Add(curip); } } } if (curif != null) mySysInfo.Interfaces.Add(curif); }
private void cmdOK_Click(object sender, EventArgs e) { String app = Path.Combine(solutionDirectory, (String) lstLaunchItems.SelectedItem); CloverleafEnvironment.RemoteServerHost = txtHostName.Text; this.Hide(); String host = txtHostName.Text; String user = txtUsername.Text; String password = txtPassword.Text; String zipDirectory = CloverleafEnvironment.CloverleafAppDataPath; String zipFileName = host + "." + user + "." + DateTime.Now.Ticks.ToString() + ".zip"; String zipPath = Path.Combine(zipDirectory, zipFileName); String scriptPath = Path.Combine(zipDirectory, DateTime.Now.Ticks.ToString() + ".sh"); String remoteExecutable = Path.GetFileName(app); String remoteDirectory = Path.GetFileNameWithoutExtension(zipFileName); FastZip fz = new FastZip(); fz.CreateEmptyDirectories = true; fz.RestoreAttributesOnExtract = true; fz.RestoreDateTimeOnExtract = true; fz.CreateZip(zipPath, Path.GetDirectoryName(app), true, null); ProcessStartInfo xInfo = new ProcessStartInfo(); xInfo.FileName = CloverleafEnvironment.XPath; xInfo.Arguments = "-ac -internalwm"; Process xProcess = new Process(); xProcess.StartInfo = xInfo; xProcess.Start(); 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 = "#! /bin/bash" + "\n" + "export DISPLAY=" + cboLocalIPs.SelectedItem.ToString() + ":0.0" + "\n" + "cd /home/" + user + "/.cloverleaf" + "\n" + "mkdir " + remoteDirectory + "\n" + "cp " + zipFileName + " " + remoteDirectory + "\n" + "cd " + remoteDirectory + "\n" + "unzip " + zipFileName + " > /dev/null \n" + "mono " + remoteExecutable + "\n" + "cd /home/" + user + "/.cloverleaf" + "\n" + "rm " + zipFileName + "\n" + "rm -rf " + remoteDirectory + "\n" + "rm /home/" + user + "/.cloverleaf/" + Path.GetFileName(scriptPath); File.WriteAllText(scriptPath, ssh1ArgumentData); if (scp.Connected == false) { throw new SshTransferException("Couldn't connect to host with SCP."); } scp.Put(scriptPath, "/home/" + user + "/.cloverleaf/" + Path.GetFileName(scriptPath)); 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 RemoteStdOutDisplay(stdOut, stdErr)).Show(); }
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(); }
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; }
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 Main(string[] args) { var env = environments["vagrant"]; var localPath = "Z:\\WindowsDev\\Gateway\\"; var remoteFilePath = "/home/tripservice/servicestack/"; var host = env.host; var user = env.user; var password = env.password; var sshPort = env.sshPort; var monoServer = "http://" + host + "/"; var webServer = "http://" + host + ":8080/"; 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 !"); if (fullDeploy) { //Remove any old files and upload projects Console.WriteLine("Uploading projects"); ssh.RunCommand("cd " + remoteFilePath); ssh.RunCommand("rm -rf " + remoteFilePath + "ServiceStack.* Booking*"); ssh.RunCommand("mkdir -p " + remoteFilePath + "ServiceStack.TripThruGateway/Web"); ssh.RunCommand("mkdir -p " + remoteFilePath + "ServiceStack.TripThruPartnerGateway/Web"); ssh.RunCommand("mkdir -p " + remoteFilePath + "BookingWebsite"); var omittedDirectories = new List<string> { "packages" }; UploadDirectory(localPath + "BookingWebsite", remoteFilePath + "BookingWebsite"); UploadDirectory(localPath + "ServiceStack.TripThruGateway/Web", remoteFilePath + "ServiceStack.TripThruGateway/Web"); UploadDirectory(localPath + "ServiceStack.TripThruPartnerGateway/Web", remoteFilePath + "ServiceStack.TripThruPartnerGateway/Web"); ssh.RunCommand("mv " + remoteFilePath + "ServiceStack.TripThruGateway/Web/mono/* " + remoteFilePath + "ServiceStack.TripThruGateway/Web/bin"); ssh.RunCommand("mv " + remoteFilePath + "ServiceStack.TripThruPartnerGateway/Web/mono/* " + remoteFilePath + "ServiceStack.TripThruPartnerGateway/Web/bin"); } var webappNames = new List<string>(); string[] partnerConfigurations = Directory.GetFiles("PartnerConfigurations/", "*.txt"); List<string> partnerscallbackUrlMono = new List<string>(); foreach (var partnerConfiguration in partnerConfigurations) { var configuration = JsonSerializer.DeserializeFromString<PartnerConfiguration>(File.ReadAllText(partnerConfiguration)); configuration.TripThruUrlMono = monoServer + configuration.TripThruUrlMono; configuration.Partner.CallbackUrlMono = monoServer + configuration.Partner.CallbackUrlMono; configuration.Partner.WebUrl = webServer + configuration.Partner.WebUrl; string configStr = JsonSerializer.SerializeToString<PartnerConfiguration>(configuration); File.WriteAllText(partnerConfiguration, configStr); if (configuration.Enabled) { partnerscallbackUrlMono.Add(configuration.Partner.CallbackUrlMono); var name = configuration.Partner.Name.Replace(" ", ""); Console.WriteLine("Configuring " + name); webappNames.Add(name); ssh.RunCommand("cp -a " + remoteFilePath + "ServiceStack.TripThruPartnerGateway/ " + remoteFilePath + "ServiceStack." + name + "/"); ssh.RunCommand("rm " + remoteFilePath + "ServiceStack." + name + "/Web/PartnerConfiguration.txt"); sftpBase.Put(partnerConfiguration, remoteFilePath + "ServiceStack." + name + "/Web/PartnerConfiguration.txt"); var bookingwebConfig = new System.IO.StreamWriter("config.txt"); bookingwebConfig.WriteLine("HomeUrl=" + configuration.Partner.WebUrl); bookingwebConfig.WriteLine("RelativeHomeUrl=" + configuration.Partner.WebUrlRelative); bookingwebConfig.WriteLine("TripThruUrl=" + configuration.TripThruUrlMono); bookingwebConfig.WriteLine("TripThruAccessToken=" + "jaosid1201231"); //fixed tripthru access token bookingwebConfig.WriteLine("PartnerUrl=" + configuration.Partner.CallbackUrlMono); bookingwebConfig.WriteLine("PartnerAccessToken=" + configuration.Partner.AccessToken); bookingwebConfig.WriteLine("PartnerName=" + name); bookingwebConfig.WriteLine("PartnerId=" + configuration.Partner.ClientId); bookingwebConfig.Flush(); bookingwebConfig.Close(); ssh.RunCommand("rm " + remoteFilePath + "BookingWebsite/inc/tripthru/config.txt"); sftpBase.Put("config.txt", remoteFilePath + "BookingWebsite/inc/tripthru/"); ssh.RunCommand("rm " + remoteFilePath + "BookingWebsite/images/taxi-cars_logo.png"); var x = name + ".png"; var y = remoteFilePath + "BookingWebsite/images/taxi-cars_logo.png"; sftpBase.Put("PartnerConfigurations/" + name + ".png", remoteFilePath + "BookingWebsite/images/taxi-cars_logo.png"); ssh.RunCommand("rm -rf /var/www/sanfran/Bookings" + name); ssh.RunCommand("cp -a " + remoteFilePath + "BookingWebsite/ /var/www/sanfran/Bookings" + name); } } if (fullDeploy) { //create fast-cgi mono webapp config var webappConfig = new System.IO.StreamWriter("tripthru.webapp"); webappConfig.WriteLine("<apps>"); webappConfig.Flush(); webappConfig.WriteLine(@"<web-application> <name>TripThru.TripThruGateway</name> <vhost>*</vhost> <vport>80</vport> <vpath>/TripThru.TripThruGateway</vpath> <path>/var/www/ServiceStack.TripThruGateway/Web</path> </web-application>" ); webappConfig.Flush(); foreach (var webapp in webappNames) { webappConfig.WriteLine(@"<web-application> <name>TripThru.{0}</name> <vhost>*</vhost> <vport>80</vport> <vpath>/TripThru.{0}</vpath> <path>/var/www/ServiceStack.{0}/Web</path> </web-application>", webapp ); webappConfig.Flush(); } webappConfig.WriteLine("</apps>"); webappConfig.Flush(); webappConfig.Close(); Console.WriteLine("Updating mono webapp config"); ssh.RunCommand("rm /etc/rc.d/init.d/mono-fastcgi/tripthru.webapp"); sftpBase.Put("tripthru.webapp", "/etc/rc.d/init.d/mono-fastcgi/tripthru.webapp"); } Console.WriteLine("Stopping mono"); ssh.RunCommand("kill -9 $(netstat -tpan |grep \"LISTEN\"|grep :9000|awk -F' ' '{print $7}'|awk -F'/' '{print $1}')"); Console.WriteLine("Updating web folder"); ssh.RunCommand("rm -rf /var/www/ServiceStack.*"); ssh.RunCommand("cp -a " + remoteFilePath + "/ServiceStack.* /var/www/"); Thread startMono = new Thread( delegate() { Console.WriteLine("Starting mono"); ssh.RunCommand("export MONO_OPTIONS=\"--debug\""); ssh.RunCommand("fastcgi-mono-server4 --appconfigdir /etc/rc.d/init.d/mono-fastcgi /socket=tcp:127.0.0.1:9000 /logfile=/var/log/mono/fastcgi.log &"); }); startMono.Start(); Console.WriteLine("Sleep 8 seconds, waiting for mono to initialize."); Thread.Sleep(8000); var client = new System.Net.WebClient(); foreach (string callbackUrlMono in partnerscallbackUrlMono) { Console.WriteLine("Sending request to: \n" + @callbackUrlMono.ToString() + "log"); while (true) { try { var response = client.DownloadString(@callbackUrlMono.ToString() + "log"); var analyzeResponse = JsonSerializer.DeserializeFromString<ResponseRequest>(response); if (analyzeResponse.ResultCode.Equals("OK")) { Console.WriteLine("Correct."); break; } else { Thread.Sleep(1000); } } catch (Exception ex) { } } } Console.WriteLine("Done!"); startMono.Abort(); sftpBase.Close(); ssh.Close(); }
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; } }
/***************************************************************************** * @author Alex Wulff * * @par Description: * This method tests the vm for build success * *****************************************************************************/ private bool BuildSuccess() { SshExec exec = new SshExec(_SSHIP, _VMUsername, _VMPassword); exec.Connect(); string stdOut = null; string stdError = null; exec.RunCommand("./svnUpdate", ref stdOut, ref stdError); exec.RunCommand("./buildTests", ref stdOut, ref stdError); exec.RunCommand("./validateBuildTests", ref stdOut, ref stdError); if (stdError.Length != 0 || stdOut.Length != 0) { _ErrorMessages = string.Format("{0},{1}", stdOut, stdError).ToString(); } else { _ErrorMessages = ""; return true; } Console.WriteLine(stdOut); exec.Close(); return false; }
private static void getMACAIX(SshExec exec, InterfaceState curif) { char[] lineseps = { '\r', '\n' }; char[] fieldseps = { ' ', '\t' }; char[] onlydot = { '.' }; string output = exec.RunCommand("netstat -I " + curif.Name); string[] lines = output.Split(lineseps, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { string[] pfields = line.Split(fieldseps, StringSplitOptions.RemoveEmptyEntries); if (pfields.GetUpperBound(0) >= 3) { string maybeMAC = pfields[3]; string[] bytesMAC = maybeMAC.Split(onlydot, StringSplitOptions.None); if (bytesMAC.GetUpperBound(0) == 5) { try { curif.HWAddr = String.Format("{0}:{1}:{2}:{3}:{4}:{5}", Convert.ToUInt32(bytesMAC[0], 16).ToString("X2"), Convert.ToUInt32(bytesMAC[1], 16).ToString("X2"), Convert.ToUInt32(bytesMAC[2], 16).ToString("X2"), Convert.ToUInt32(bytesMAC[3], 16).ToString("X2"), Convert.ToUInt32(bytesMAC[4], 16).ToString("X2"), Convert.ToUInt32(bytesMAC[5], 16).ToString("X2")); return; } catch { } } } } }