Example #1
0
        private void fillVideoFiles()
        {
            string output = exec.RunCommand(String.Format("ls {0}", videoFolder));

            foreach (string file in output.Split('\n'))
            {
                if (file == "" || file == " ")
                {
                    continue;
                }
                videos.Add(file);
            }
        }
Example #2
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();
        }
Example #3
0
 void Command.issueCommand()
 {
     exec.Connect();
     exec.RunCommand("sudo reboot");
     exec.Close();
     return;
 }
Example #4
0
        private void backgroundWorkerLog_DoWork(object sender, DoWorkEventArgs e)
        {
            String preStr = "";

            while (true)
            {
                try
                {
                    // 获取日志
                    String   str = exec2.RunCommand("tail -100 /tmp/pppoe.log");
                    String[] opt = GetLastUpdateLog(preStr, str);
                    if (backgroundWorkerLog.CancellationPending)
                    {
                        exec2.Close();
                        break;
                    }
                    this.Invoke(new UpdateLogCallback(UpdateLogContent), new Object[] { opt });
                    preStr = str;
                } catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                Thread.Sleep(1000);
            }
        }
        private void btnCMD_Click(object sender, EventArgs ee)
        {
            try
            {
                //  SshConnectionInfo input = Util.GetInput();
                SshExec exec = new SshExec(txtHost.Text, txtUser.Text);
                exec.Password = txtPassword.Text;
                //  if (input.Pass != null) exec.Password = input.Pass;
                //   if (input.IdentityFile != null) exec.AddIdentityFile(input.IdentityFile);

                AppendText("Connecting...");
                exec.Connect();
                AppendText("Connect OK");

                string command = txtCMD.Text;
                if (command != "")
                {
                    exec.RunCommand(command);
                }

                AppendText("Disconnecting...");
                exec.Close();
                AppendText(" Disconnecting OK");
            }
            catch (Exception e)
            {
                AppendText(e.Message);
            }
        }
Example #6
0
        public void RunShellTest()
        {
            try
            {
                shell.Connect();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            shell.ExpectPattern = "#";
            Console.WriteLine(shell.Expect());
            shell.WriteLine(@"ls");
            Console.WriteLine(shell.Expect());
            shell.WriteLine(@"ll");
            Console.WriteLine(shell.Expect());
            shell.WriteLine(@"cd /usr/local");
            Console.WriteLine(shell.Expect());
            shell.WriteLine(@"ll");
            Console.WriteLine(shell.Expect());
            shell.WriteLine(@"topp");
            Console.WriteLine(shell.Expect());

            shell.Close();


            Console.WriteLine("----------------------------------------------");

            exec.Connect();
            string strRrr = "";
            string strOut = "";

            exec.RunCommand("ls", ref strOut, ref strRrr);
            System.Threading.Thread.Sleep(1000);
            Console.WriteLine(strOut);
            Console.WriteLine(strRrr);

            exec.RunCommand(@"cd /usr/local", ref strOut, ref strRrr);
            Console.WriteLine(strOut);
            Console.WriteLine(strRrr);


            Console.WriteLine(exec.RunCommand(@"ll"));
            Console.WriteLine(exec.RunCommand(@"cd /usr/local"));

            exec.Close();
        }
Example #7
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 #8
0
        public void ExecuteCommand(String command)
        {
            using (var ssh = new SshExec(host, user, pass))
            {
                ssh.Connect();

                ssh.RunCommand(command);
            }
        }
Example #9
0
        public void ExecuteCommand(String command)
        {
            using (var ssh = new SshExec(host, user, pass))
            {
                ssh.Connect();

                ssh.RunCommand(command);
            }
        }
Example #10
0
        private string SshExec(string ssh_cmd)
        {
            string  result = "";
            SshExec exec   = SshConnect(ProgramSettings.settings.SshHost, ProgramSettings.settings.SshPort,
                                        ProgramSettings.settings.SshLogin, ProgramSettings.settings.SshPass, ProgramSettings.settings.SshKey);

            result = exec.RunCommand(ssh_cmd).Replace("\n", " ");
            exec.Close();
            return(result);
        }
Example #11
0
        }     // end EjecutarSHH

        public static string test()
        {
            //Establecemos la conexión SSH
            const string host    = "tmpsao445674";
            SshExec      sshExec = new SshExec(host, "tomcat", "XXXsrivera445674");

            sshExec.Connect();

            string result = sshExec.RunCommand(@"cat /etc/redis.conf");

            return(result);
        }
Example #12
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();
        }
        private String getMeLastModificationTime(String serverPath)
        {
            String stdOut = null;
            String stdErr = null;
            // need to send following cmd: stat serverPath | grep -E ^M | cut -d' ' -f2
            String cmdToExec = "stat " + serverPath + " | grep -E ^M | cut -d' ' -f2";

            mySshExec = new SshExec(ftpAdr, user, password);
            mySshExec.Connect();
            mySshExec.RunCommand(cmdToExec, ref stdOut, ref stdErr);
            mySshExec.Close();
            //Debug.Print("Data pliku na serwerze " + stdOut);
            return(stdOut);
        }
Example #14
0
 private void backgroundWorkerStatus_DoWork(object sender, DoWorkEventArgs e)
 {
     while (true)
     {
         try
         {
             // 获取接口状态
             String uciCom = exec.RunCommand("uci show network | grep -E \"(network\\.)\\w+(\\.proto='pppoe')\" | cut -d . -f 2");
             ifList = uciCom.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
             List <InterfaceStatus> list = new List <InterfaceStatus>();
             foreach (String ifname in ifList)
             {
                 String          eth = exec.RunCommand("uci show network." + ifname + ".ifname | cut -d = -f 2 | cut -d \\' -f 2");
                 String          res = exec.RunCommand("ifconfig | grep pppoe-" + ifname);
                 InterfaceStatus ifs = new InterfaceStatus(ifname, false);
                 ifs.Eth = eth;
                 if (!res.Trim().Equals(""))
                 {
                     String user = exec.RunCommand("uci show network." + ifname + ".username | cut -d = -f 2 | cut -c 13-23");
                     ifs.UserName = user;
                     ifs.OnLine   = true;
                 }
                 list.Add(ifs);
             }
             if (backgroundWorkerStatus.CancellationPending)
             {
                 exec.Close();
                 break;
             }
             this.Invoke(new UpdateInterfaceStatucCallback(UpdateInterfaceStatus), list);
         } catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
         Thread.Sleep(1000);
     }
 }
Example #15
0
        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 #16
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 #17
0
        public void runCommand(string command, string stdout = "", string stderr = "")
        {
            _shell.Connect();
            _shell.RedirectToConsole();
            _exec.Connect();

            int ret = _exec.RunCommand(command, ref stdout, ref stderr);

            if (ret != 0)
            {
                System.Diagnostics.Debugger.Break();
            }

            _exec.Close();
            _shell.Close();
        }
Example #18
0
        private static void UploadDirectory(string dirPath, string uploadPath)
        {
            string[] files   = Directory.GetFiles(dirPath, "*.*");
            string[] subDirs = Directory.GetDirectories(dirPath);

            foreach (string file in files)
            {
                sftpBase.Put(file, uploadPath + "/" + Path.GetFileName(file));
            }

            foreach (string subDir in subDirs)
            {
                ssh.RunCommand("mkdir " + uploadPath + "/\"" + Path.GetFileName(subDir) + "\"");
                UploadDirectory(subDir, uploadPath + "/" + Path.GetFileName(subDir));
            }
        }
        public static SshRemoteProcess CreateProcess(MeeGoExecutionCommand cmd, string sdbOptions, MeeGoDevice device,
                                                     Dictionary <string, string> xauth,
                                                     Action <string> stdOut, Action <string> stdErr)
        {
            string exec = GetCommandString(cmd, sdbOptions, xauth);

            var ssh = new LiveSshExec(device.Address, device.Username, device.Password);

            //hacky but openssh seems to ignore signals
            Action kill = delegate {
                var killExec = new SshExec(device.Address, device.Username, device.Password);
                killExec.Connect();
                killExec.RunCommand("ps x | grep '" + cmd.DeviceExePath + "' | " +
                                    "grep -v 'grep \\'" + cmd.DeviceExePath + "\\' | awk '{ print $1 }' | xargs kill ");
                killExec.Close();
            };

            return(new SshRemoteProcess(ssh, exec, stdOut, stdErr, kill));
        }
Example #20
0
        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);
            }
        }
Example #21
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;
                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 #22
0
        public string ExecuteCMD(string cmd)
        {
            if (!shell.Connected)
            {
                return("");
            }

            string output = "";

            try
            {
                output = shell.RunCommand(cmd);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error when execute command by SSH. [{0}]", e.Message);
            }

            return(output);
        }
Example #23
0
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                SshExec shell = new SshExec(ADDRESS_SERVEUR_TELNET, LOGIN_SERVEUR_TELNET, PASSWD_SERVEUR_TELNET);

                ShellBox.AppendText("Connecting...\n");

                shell.Connect();

                if (shell.Connected == true)
                {
                    ShellBox.AppendText("Connexion OK\n");

                    //while (true)
                    //{
                    System.Threading.Thread.Sleep(500);
                    string output = shell.RunCommand(@"tail -f \gsoap\log\VSSrvConnexionGS.log");
                    ShellBox.AppendText(output + "\n");
                    //}
                    ShellBox.AppendText("Disconnecting...\n");
                    shell.Close();
                    if (shell.Connected == false)
                    {
                        ShellBox.AppendText("Deconnexion OK\n");
                    }
                    else
                    {
                        ShellBox.AppendText("Deconnexion KO\n");
                    }
                }
                else
                {
                    ShellBox.AppendText("Connexion KO\n");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
Example #24
0
        //WPF로 파일 업로드 (localfile : 컴퓨터 파일 경로, hwak : 확장자, std_no : 학번)
        //설치 순서 주의! - packages폴더에 dll이 있어야함.
        //사용시 https://sourceforge.net/projects/sharpssh/ 에서 다운한 파일 중 'Tamir.SharpSSH.dll'을 참조 후 누겟의 Tamir.SharpSSH 설치, 그 후 앞서 참조한 dll 참조 지우기
        private void Uploadimg(string localfile, string hwak, string std_no)
        {
            Sftp oSftp = null;

            try
            {
                SshExec se = new SshExec("l.bsks.ac.kr", "p201606023", "pp201606023");
                se.Connect(22);
                string dir = "/home/p201606023/public_html/image/";
                se.RunCommand("rm " + dir + std_no + ".jpg");
                se.RunCommand("rm " + dir + std_no + ".jpeg");
                se.RunCommand("rm " + dir + std_no + ".png");
                se.RunCommand("rm " + dir + std_no + ".gif");
                se.RunCommand("rm " + dir + std_no + ".JPG");
                se.RunCommand("rm " + dir + std_no + ".PNG");
                se.RunCommand("rm " + dir + std_no + ".GIF");
                se.Close();

                string _ftpURL       = "l.bsks.ac.kr";                        //Host URL or address of the SFTP server
                string _UserName     = "******";                          //User Name of the SFTP server
                string _Password     = "******";                         //Password of the SFTP server
                int    _Port         = 22;                                    //Port No of the SFTP server (if any)
                string _ftpDirectory = "/home/p201606023/public_html/image/"; //The directory in SFTP server where the files will be uploaded

                oSftp = new Sftp(_ftpURL, _UserName, _Password);
                oSftp.Connect(_Port);

                oSftp.Put(localfile, _ftpDirectory + std_no + "." + hwak);
            }
            catch (Exception ex)
            {
                MessageBox.Show("이미지 저장에 실패하였습니다.\n" + ex.Message + "::" + ex.StackTrace, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;
            }
            finally
            {
                if (oSftp != null)
                {
                    oSftp.Close();
                }
            }
        }
Example #25
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);
     }
 }
Example #26
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 #27
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 #28
0
        static void Main(string[] args)
        {
            try
            {
                SshExec exec = new SshExec(ipAddress, username, password);
                Console.Write("Connecting...");
                exec.Connect();
                Console.WriteLine("OK");
                if (exec.Connected)
                {
                    Console.WriteLine(exec.Cipher);
                }

                while (true)
                {
                    Console.Write("Enter a command to execute ['Enter' to cancel]: ");
                    string command = Console.ReadLine();
                    if (command == "")
                    {
                        break;
                    }
                    string   output = exec.RunCommand(command);
                    string[] m      = output.Split('\n');
                    for (int i = 0; i < m.Length; i++)
                    {
                        Console.WriteLine(m[i]);
                    }
                }
                Console.Write("Disconnecting...");
                exec.Close();
                Console.WriteLine("OK");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #29
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 #30
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 #31
0
        private static void UploadProjects()
        {
            //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");
        }