Example #1
0
        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);
        }
Example #2
0
        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);
            }
        }
Example #3
0
        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();
        }
Example #5
0
		/// <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);
        }
Example #7
0
        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();
        }
Example #8
0
 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 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;
        }
Example #10
0
 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); }
        }
Example #13
0
        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);
            }
        }
Example #14
0
 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;
 }
Example #15
0
        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);
            }
        }
Example #16
0
        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);
            }
        }
Example #17
0
        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();
        }
Example #19
0
        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;
        }
Example #20
0
        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 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();
        }
Example #22
0
 private SshExec getCommander()
 {
     //using Tamir.SharpSsh;
     Tamir.SharpSsh.SshExec e = new SshExec(HostName, UserName, Password);
     e.Connect();
     return e;
 }
 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;
 }
Example #24
0
        // 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();
        }
Example #25
0
        internal static ESXiConnection ConnectToServer(
            ESXiConnection connection,
            string serverName,
            int port,
            string username,
            string password,
            string datastoreName)
        {
            ESXiConnection result = null;

            //            using (var client =
            //                   new SshClient(
            //                       serverName,
            //                       port,
            //                       username,
            //                       password))
            //            {
            //                client.Connect();
            //                //client.Disconnect();
            //
            //                result = client.IsConnected;
            //            }
            ////            result = client.IsConnected;

            if (connection != null ) {
                serverName = connection.Server;
                port = connection.Port;
                username = connection.Username;
                password = connection.Password;
            }
            //ESXiConnection connection = null;
            connection = null;
            if ((connection =  Connections.GetConnection(
                    serverName,
                    port,
                    username,
                    password)) == null) {

                SshExec exec =
                    new SshExec(
                        serverName,
                        username,
                        password);

                System.IO.TextWriter standardWriter =
                    Console.Out;
                System.IO.Stream stream =
                    new System.IO.MemoryStream();
                System.IO.TextWriter writer =
                    new System.IO.StreamWriter(stream);
                Console.SetOut(writer);
                exec.Connect();
                Console.SetOut(standardWriter);

                if (exec.Connected) {
                    connection =
                        new ESXiConnection(
                            serverName,
                            port,
                            username,
                            password);
                    result = Connections.Add(connection, exec);
                    //result = true;

                    //exec.Close();
                }
            }

            //            while(true)
            //            {
            //                Console.Write("Enter a command to execute ['Enter' to cancel]: ");
            //                string command = Console.ReadLine();
            //                if(command=="")break;
            //                string output = exec.RunCommand("ls");
            //                //string output = shell..RunCommand("ls");
            //                Console.WriteLine(output);
            //            }
            //            Console.Write("Disconnecting...");
            //            exec.Close();
            //shell.Close();
            //            Console.WriteLine("Closed: OK");

            return result;
        }
Example #26
0
        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 !");
        }
Example #27
0
        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 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;
            }
        }
Example #29
0
        /*****************************************************************************
         * @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;
        }