RunCommand() public method

Creates and executes the command.
This method internally uses asynchronous calls.
CommandText property is empty. Invalid Operation - An existing channel was used to execute this command. Asynchronous operation is already in progress. Client is not connected. is null.
public RunCommand ( string commandText ) : SshCommand
commandText string The command text.
return SshCommand
示例#1
0
        /// <summary>
        /// Copy from source to target
        /// </summary>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            bool success = false;
            try
            {
                Debug.WriteLine("ExtractCommand");

                var command1 = client.RunCommand("tar xzvf " + Target);
                var s1 = command1.Result;
                Output = s1;

                var command2 = client.RunCommand("echo $?");
                var s2 = command2.Result;
                
                var arrRsp = s2.Split(new[] {"\n"}, StringSplitOptions.None);

                if(arrRsp.Length > 0)
                    if (arrRsp[0] == "0")
                        success = true;

            } catch(Exception e)
            {
                Logger.Warn("Exception extracting archive: " +e.Message);
            }
            return success;
        }
示例#2
0
        public SshCommand RunSSHCommand(string userCommandText, bool throwOnError = true)
        {
            InternalConnect(_sshDeltaCopyOptions.Host, _sshDeltaCopyOptions.Port, _sshDeltaCopyOptions.Username, _sshDeltaCopyOptions.Password, _sshDeltaCopyOptions.PrivateKeyFile, _sshDeltaCopyOptions.DestinationDirectory);

            var commandText = $"cd \"{_sshDeltaCopyOptions.DestinationDirectory}\";{userCommandText}";

            PrintTime($"Running SSH command ...\n{commandText}");

            SshCommand cmd = _sshClient.RunCommand(commandText);

            if (cmd.ExitStatus != 0 || !string.IsNullOrWhiteSpace(cmd.Error))
            {
                var error = $"SSH command error: {cmd.ExitStatus}\n{cmd.CommandText}\n{cmd.Error}";
                PrintError(error);

                if (throwOnError)
                {
                    throw new Exception(error);
                }
            }

            PrintTime($"SSH command result:\n{cmd.Result}");

            return(cmd);
        }
示例#3
0
        private void button1_Click(object sender, EventArgs e)
        {
            string host = textBoxServer.Text.Trim();
            string userName = textBoxUserName.Text.Trim();
            string psw = textBoxPassword.Text.Trim();
            string url = textBoxCoomand.Text.Trim();
            string location = @" -P  " + textBoxLocation.Text.Trim();
            string finalCommand = @"wget -bqc '" + url + "' " + location + " ";
            ConnectionInfo conInfo = new ConnectionInfo(host, 22, userName, new AuthenticationMethod[]{
                new PasswordAuthenticationMethod(userName,psw)
            });
            SshClient client = new SshClient(conInfo);
            try
            {
                client.Connect();
                var outptu = client.RunCommand(finalCommand);
            }
            catch (Exception ex)
            {
                textBoxDisplay.Text = ex.Message;
                throw;
            }

            client.Disconnect();
            client.Dispose();
            SetLastValues(host, userName, psw, textBoxLocation.Text.Trim());
        }
示例#4
0
 public void Run(string cmd, string host)
 {
     try
     {
         using (SshClient c = new SshClient(host, m_userName, m_userPassword))
         {
             Log.DebugFormat("Connecting to {0} with command: {1}", host, cmd );
             c.Connect();
             SshCommand ssh = c.RunCommand(cmd);
             ExitStatus = ssh.ExitStatus;
             Result = ssh.Result;
             c.Disconnect();
             if (Result.Length == 0)
             {
                 Log.DebugFormat("Disconnecting from {0} with exit status: {1} (result is empty)", host, ExitStatus );
             }
             else
             {
                 Log.DebugFormat("Disconnecting from {0} with exit status {1} result is: " + Environment.NewLine + "{2}", host, ExitStatus, Result);
             }
         }
     }
     catch (Exception ex)
     {
         Log.ErrorFormat("Failed to connect to {0} because: {1}", host, ex);
         ExitStatus = -1;
         Result = null;
     }
 }
示例#5
0
        public override NodeResult Run()
        {
            if (string.IsNullOrEmpty(host.Value) || string.IsNullOrEmpty(user.Value) || string.IsNullOrEmpty(command.Value))
                return NodeResult.Fail;

            try
            {
                SshClient sshClient = new SshClient(host.Value, port.Value, user.Value, password.Value);
                sshClient.Connect();

                Renci.SshNet.SshCommand sshCommand = sshClient.RunCommand(command.Value);
                Log.Info(sshCommand.CommandText);

                if (!string.IsNullOrWhiteSpace(sshCommand.Result))
                    Log.Warning(sshCommand.Result);
                if (!string.IsNullOrWhiteSpace(sshCommand.Error))
                    Log.Error(sshCommand.Error);
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return NodeResult.Fail;
            }

            return NodeResult.Success;
        }
示例#6
0
        public void GetUsers(object sender, BackgroundWorker worker, Delegate sendUsers)
        {
            foreach (string host in SshSettings.Hosts())
            {
                if (worker.CancellationPending)
                    break;

                List<SshUser> users = new List<SshUser>();
                using (SshClient ssh = new SshClient(_currentUser.GetPasswordConenctionInfo(String.Concat(host, SshSettings.Domain))))
                {
                    try
                    {
                        ssh.Connect();
                        string response = ssh.RunCommand("who -u").Execute();
                        // TODO: Parse response.
                        ParseWhoResponse(response, host, ref users);
                        if (users.Count > 0)
                            ((System.Windows.Forms.Form) sender).Invoke(sendUsers, users);
                    }
                    catch (Exception ex)
                    {
                        if (ex is SshException || ex is SocketException)
                        {
                            if (ssh.IsConnected)
                                ssh.Disconnect();
                            ssh.Dispose();
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
        }
示例#7
0
 protected void RebootButton_Click(object sender, EventArgs e)
 {
     try
     {
         using (var client = new SshClient("ra-jetson.duckdns.org", "ubuntu", "savingL1v3s"))
         {
             client.Connect();
             client.RunCommand("sudo /home/ubuntu/Desktop/bandhan/SQL-Scripts/./RightAlertRemoteRebootIssued-SQL"); // SSH Command Here
             client.RunCommand("sudo reboot"); // SSH Command Here
             client.Disconnect();
         }
     }
     catch (Exception ex)
     {
         Response.Redirect("Down.html");
     }
 }
示例#8
0
    public String UploadFileToFtp(string url, string filePath)
    {
        try
        {
            var fileName = Path.GetFileName(filePath);
            Console.WriteLine(url);

            var request = (FtpWebRequest)WebRequest.Create(url + fileName);

            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential("cloudera", "cloudera");
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = false;

            using (var fileStream = File.OpenRead(filePath))
            {
                using (var requestStream = request.GetRequestStream())
                {
                    fileStream.CopyTo(requestStream);
                    requestStream.Close();
                }
            }

            var response = (FtpWebResponse)request.GetResponse();
            response.Close();

            Console.WriteLine("Subiendo archivo a hadoop");
            using (var client = new SshClient("192.168.1.6", "cloudera", "cloudera"))

            {
                client.Connect();
                client.RunCommand("hadoop fs -copyFromLocal JSON/" + fileName + " /user/JSON/"+fileName);
                client.RunCommand("rm JSON/" + fileName);
                client.Disconnect();
            }

            return "Archivo Subido con éxito";
        }
        catch (Exception ex)
        {
            return "Parece que tenemos un problema." + ex.Message;
        }
    }
示例#9
0
 public void run(string host, string user, string pass, string command)
 {
     using (var sshClient = new SshClient(host, user, pass))
     {
         sshClient.Connect();
         sshClient.RunCommand(command);
         sshClient.Disconnect();
         sshClient.Dispose();
     }
 }
示例#10
0
        public SshCommand RunSSHCommand(string userCommandText, bool throwOnError = true)
        {
            InternalConnect(_sshDeltaCopyOptions.Host, _sshDeltaCopyOptions.Port, _sshDeltaCopyOptions.Username, _sshDeltaCopyOptions.Password, _sshDeltaCopyOptions.DestinationDirectory);

            var commandText = $"cd \"{_sshDeltaCopyOptions.DestinationDirectory}\";{userCommandText}";

            PrintTime($"Running SSH command ...\n{commandText}");

            SshCommand cmd = _sshClient.RunCommand(commandText);

            if (throwOnError && cmd.ExitStatus != 0)
            {
                throw new Exception(cmd.Error);
            }

            PrintTime($"SSH command result:\n{cmd.Result}");

            return(cmd);
        }
示例#11
0
        public void beginCracking()
        {
            log("beginning cracking process..");
            var connectionInfo = new PasswordConnectionInfo (xml.Config.host, xml.Config.port, "root", xml.Config.Password);
            using (var sftp = new SftpClient(connectionInfo))
            {
                using (var ssh = new SshClient(connectionInfo))
                {
                    PercentStatus("Establishing SSH connection", 5);
                    ssh.Connect();
                    PercentStatus("Establishing SFTP connection", 10);
                    sftp.Connect();

                    log("Cracking " + ipaInfo.AppName);
                    PercentStatus("Preparing IPA", 25);
                    String ipalocation = AppHelper.extractIPA(ipaInfo);
                    using (var file = File.OpenRead(ipalocation))
                    {
                        log("Uploading IPA to device..");
                        PercentStatus("Uploading IPA", 40);
                        sftp.UploadFile(file, "Upload.ipa");

                    }
                    log("Cracking! (This might take a while)");
                    PercentStatus("Cracking", 50);
                    String binaryLocation = ipaInfo.BinaryLocation.Replace("Payload/", "");
                    String TempDownloadBinary = Path.Combine(AppHelper.GetTemporaryDirectory(), "crackedBinary");
                    var crack = ssh.RunCommand("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                    log("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                    log("cracking output: " + crack.Result);

                    using (var file = File.OpenWrite(TempDownloadBinary))
                    {
                        log("Downloading cracked binary..");
                        PercentStatus("Downloading cracked binary", 80);
                        try
                        {
                            sftp.DownloadFile("/tmp/crackedBinary", file);
                        }
                        catch (SftpPathNotFoundException e)
                        {
                            log("Could not find file, help!!!!!");
                            return;
                        }
                    }

                    PercentStatus("Repacking IPA", 90);
                    String repack = AppHelper.repack(ipaInfo, TempDownloadBinary);
                    PercentStatus("Done!", 100);

                    log("Cracking completed, file at " + repack);
                }
            }
        }
示例#12
0
        public static void flash_px4(string firmware_file)
        {
            if (is_solo_alive)
            {
                using (SshClient client = new SshClient("10.1.1.10", 22, "root", "TjSDBkAu"))
                {
                    client.KeepAliveInterval = TimeSpan.FromSeconds(5);
                    client.Connect();

                    if (!client.IsConnected)
                        throw new Exception("Failed to connect ssh");

                    var retcode = client.RunCommand("rm -rf /firmware/loaded");
                    
                    using (ScpClient scpClient = new ScpClient(client.ConnectionInfo))
                    {
                        scpClient.Connect();

                        if (!scpClient.IsConnected)
                            throw new Exception("Failed to connect scp");

                        scpClient.Upload(new FileInfo(firmware_file), "/firmware/" + Path.GetFileName(firmware_file));
                    }

                    var st = client.CreateShellStream("bash", 80, 24, 800, 600, 1024*8);

                    // wait for bash prompt
                    while (!st.DataAvailable)
                        System.Threading.Thread.Sleep(200);

                    st.WriteLine("loadPixhawk.py; exit;");
                    st.Flush();

                    StringBuilder output = new StringBuilder();

                    while (client.IsConnected)
                    {
                        var line = st.Read();
                        Console.Write(line);
                        output.Append(line);
                        System.Threading.Thread.Sleep(100);

                        if (output.ToString().Contains("logout"))
                            break;
                    }
                }
            }
            else
            {
                throw new Exception("Solo is not responding to pings");
            }
        }
示例#13
0
        /// <summary>
        /// Copy from source to target
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            try
            {
                var command1 = client.RunCommand("rm -Rf " + Target);
                return command1.ExitStatus == 0;

            } catch(Exception e)
            {
                Logger.Warn("Exception deleting files: " +e.Message);
            }
            return false;
        }
示例#14
0
        private void btn_Q1_Click(object sender, EventArgs e)
        {
            Renci.SshNet.SshClient _session = new Renci.SshNet.SshClient(txt_ip1.Text, txt_user1.Text, txt_pwd1.Text);

            SshCommand x = sshC.RunCommand(txt_cmd1.Text);

            //SshCommand z2 = sshC.RunCommand(txt_cmd1.Text);
            //string z1 = z2.Execute(txt_cmd1.Text);

            txt_Show1.Text = "结果信息\n" + x.Result + "错误信息:" + x.Error;

            // txt_Show1.Text += "错误信息\n" + x.Error;
            //txt_Show1.Text += z1;
        }
示例#15
0
        public object Bootstrap(Drone drone)
        {
            using (var ssh = new SshClient(ChefHost, "root", "0953acb"))
            {
                ssh.Connect();
                var cmd = ssh.RunCommand(string.Format("knife bootstrap {0} -x root -P 0953acb --sudo -N {1} --run-list speedymailer-drone -E xomixfuture", drone.Id, Guid.NewGuid().ToString().Replace("-", "")));   //  very long list
                ssh.Disconnect();

                return new
                {
                    Drone = drone,
                    Data = cmd.Result.Replace("\n", "<br>")
                };
            }
        }
示例#16
0
 public string sshRunCommand(string command)
 {
     if (ssh.IsConnected)
     {
         SshCommand cmd = ssh.RunCommand(command);
         if (cmd.ExitStatus == 0)
         {
             return(cmd.Result + "\n");
         }
         else
         {
             return("Error " + cmd.Error + "\n");
         }
     }
     return("Warning: not connected to SSH");
 }
示例#17
0
        //Same as returnSSH, but specific a specific server isntead of a the generic RPI server
        public string returnSSHFrom(string passedCommand, string passedServer)
        {
            SshClient AuthClient = new SshClient(passedServer, username, password);

            try
            {
                AuthClient.Connect();
                SshCommand RunCommand = AuthClient.RunCommand(passedCommand);
                AuthClient.Disconnect();
                return RunCommand.Result;
            }
            catch
            {
                return "";
            }
        }
示例#18
0
        private string username = ""; //private store for username and password

        #endregion Fields

        #region Methods

        //Use stored infor to run comamnds on a server
        public string returnSSH(string passedCommand)
        {
            SshClient AuthClient = new SshClient("rcs.rpi.edu", username, password);

            try
            {
                AuthClient.Connect();
                SshCommand RunCommand = AuthClient.RunCommand(passedCommand);
                AuthClient.Disconnect();
                return RunCommand.Result;
            }
            catch
            {
                return "";
            }
        }
示例#19
0
        private string SshExec(ResourceNode node, string command, string args = "")
        {
            lock (_lock)
            {
                int    sshResult  = 0;
                string sshOut     = "";
                string sshErr     = "";
                string sshCommand = command + " " + args;

                var sshExec = new Ssh2
                              .SshClient(node.NodeAddress, node.Credentials.Username, node.Credentials.Password);
                //.SshExec(node.NodeAddress, node.Credentials.Username, node.Credentials.Password);

                try
                {
                    sshExec.Connect();
                    //sshResult = sshExec.RunCommand(sshCommand, ref sshOut, ref sshErr);
                    var ssh = sshExec.RunCommand(sshCommand);
                    ssh.Execute();

                    sshResult = ssh.ExitStatus;
                    sshErr    = ssh.Error;
                    sshOut    = ssh.Result;
                }
                catch (Exception e)
                {
                    Log.Warn(e.Message);
                    throw;
                }
                finally
                {
                    if (sshExec.IsConnected)
                    {
                        sshExec.Disconnect();
                    }
                }

                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);
            }
        }
示例#20
0
        public static string SendCommand(string address, string username, string password, string scriptName, string scriptArguments)
        {
            try
            {
                SshClient client = new SshClient(address, username, password);
                client.Connect();
                if (client.IsConnected)
                {
                    client.RunCommand(scriptName + " " + scriptArguments);
                }
                client.Disconnect();
            }
            catch (Exception e)
            {
                return e.Message;
            }

            return null;
        }
示例#21
0
        public List <CommandResult> ExecuteCommands(List <string> commands, ILog log)
        {
            var results = new List <CommandResult>();

            var connectionInfo = GetConnectionInfo(_config);

            using (var ssh = new Renci.SshNet.SshClient(connectionInfo))
            {
                try
                {
                    ssh.Connect();

                    foreach (var command in commands)
                    {
                        try
                        {
                            var cmd = ssh.RunCommand(command);

                            results.Add(new CommandResult {
                                Command = command, Result = cmd.Result, IsError = false
                            });
                        }
                        catch (Exception exp)
                        {
                            results.Add(new CommandResult {
                                Command = command, Result = exp.ToString(), IsError = true
                            });
                            break;
                        }
                    }

                    ssh.Disconnect();
                }
                catch (Exception e)
                {
                    log?.Error($"SShClient :: Error executing command {e}");
                }
            }

            return(results);
        }
示例#22
0
        public static string SshExec(string host, int port, string username, string password, string command)
        {
            var sshClient = new SshClient(host, port, username, password);
            sshClient.Connect();
            var executedCommand = sshClient.RunCommand(command);

            var result = string.Format("Result: {0}\r\nExitStatus: {1}\r\nError: {2}",
                                       executedCommand.Result,
                                       executedCommand.ExitStatus,
                                       executedCommand.Error);
            Console.WriteLine(result);

            if (executedCommand.ExitStatus == 0)
            {
                return executedCommand.Result;
            }
            else
            {
                throw new Exception(result);
            }
        }
示例#23
0
 protected void LoginControl_Authenticate(object sender, AuthenticateEventArgs e)
 {
     bool authenticated = this.ValidateCredentials(LoginControl.UserName, LoginControl.Password);
     /// UPDATE ACtIVITY FEED WITH LOGON
     if (authenticated)
     {
         FormsAuthentication.RedirectFromLoginPage(LoginControl.UserName, LoginControl.RememberMeSet);
         try
         {
             using (var client = new SshClient("ra-jetson.duckdns.org", "ubuntu", "savingL1v3s"))
             {
                 client.ConnectionInfo.RetryAttempts = 1;
                 client.Connect();
                 client.RunCommand("sudo /home/ubuntu/Desktop/bandhan/SQL-Scripts/./UserLogon-SQL " + LoginControl.UserName.Trim().ToLower()); // SSH Command Here
                 client.Disconnect();
             }
         }
         catch (Exception ex)
         {
             Response.Redirect("~/Down.html");
         }
     }
 }
示例#24
0
        private void backgroundWorkerConnect_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                Connection = new SshClient(_ip.ToString(), Settings.Default.DefaultPort, "pi", "raspberry");
                Connection.Connect();

                var c = Connection.RunCommand("cat /boot/customizer.txt");
                c.Execute();

                if (String.IsNullOrEmpty(c.Error))
                {
                    Configuration = c.Result;
                }
                else
                {
                    e.Result = c.Error;
                    Connection.Disconnect();
                }
            }
            catch
            {
            }
        }
示例#25
0
        private void btn_C2_Click(object sender, EventArgs e)
        {
            /*
             * Resources.HOST 192.168.10.131
             * Resources.PORT 22
             * Resources.USERNAME root
             * proxyHost
             * Resources.PORT
             * Resources.USERNAME
             * Resources.PASSWORD
             * Resources.USERNAME
             */
            var connectionInfo = new ConnectionInfo("10.69.66.67", 22, "toor4nsn",
                                                    ProxyTypes.None, "192.168.253.18", 22, "toor4nsn", "oZPS0POrRieRtu",
                                                    new KeyboardInteractiveAuthenticationMethod("10.69.66.67"));


            Renci.SshNet.SshClient _session2 = new Renci.SshNet.SshClient(connectionInfo);
            _session2.Connect();
            _session2.RunCommand("lst");

            //Renci.SshNet.Session zz = new Renci.SshNet.Session(,);
            //xx.Start();
        }
示例#26
0
        private void btn_Q2_Click(object sender, EventArgs e)
        {
            sshC = new SshClient("192.168.10.131", "root", "123123");

            sshC.KeepAliveInterval      = new TimeSpan(0, 0, 30);
            sshC.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
            sshC.Connect();

            // 动态链接
            ForwardedPortDynamic port = new ForwardedPortDynamic("127.0.0.1", 22);

            sshC.AddForwardedPort(port);
            port.Start();

            ////var fport = new ForwardedPortRemote("192.168.10.131", 22, "127.0.0.1", 22);
            ////sshC.AddForwardedPort(fport);
            ////fport.Start();

            ////string x = sshC.RunCommand("pwd").Result;
            ;
            string x = sshC.RunCommand("pwd").Result;

            ;
        }
        public void PrintFile(string fileName, string printerName)
        {
            string commands = CreatePrintFileCommand(fileName, printerName);
            try
            {
                using (var client = new SshClient(_address, _username, _password))
                {
                    client.Connect();
                    Console.WriteLine("Executing printing command, waiting for response...");
                    SshCommand result = client.RunCommand(commands);
                    string resultString = result.Result.Trim('\n', '\r', ' ');
                    Console.WriteLine("Response message is: " + resultString);

                    if (resultString.Contains("request id"))
                    {
                        Console.WriteLine("Your documents printing job is SUCCESSFULLY requested.");
                    }
                    else
                    {
                        Console.WriteLine("FAILED to executing printing command.");
                    }
                    client.Disconnect();
                }
            }
            catch (Renci.SshNet.Common.SshConnectionException)
            {
                Console.WriteLine("Cannot connect to the server.");
            }
            catch (System.Net.Sockets.SocketException)
            {
                Console.WriteLine("Unable to establish the socket.");
            }
            catch (Renci.SshNet.Common.SshAuthenticationException)
            {
                Console.WriteLine("Authentication of SSH session failed.");
            }
            Console.ReadLine();
        }
        private bool ExecuteSshCommand(string deviceName, SshClient client, string commandText)
        {
            SshCommand command = client.RunCommand(commandText);
            var success = command.ExitStatus == 0;

            if (!success)
                PostNotification(string.Format("{0}: {1}", deviceName, command.Error), NotificationKind.Danger);

            return success;
        }
        public static async Task<SshCommand> RunCommand(string command, ConnectionUser user)
        {
            ConnectionInfo connectionInfo;
            switch (user)
            {
                case ConnectionUser.Admin:
                    connectionInfo = s_adminConnectionInfo;
                    break;
                case ConnectionUser.LvUser:
                    connectionInfo = s_lvUserConnectionInfo;
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(user), user, null);
            }

            using (SshClient ssh = new SshClient(connectionInfo))
            {
                try
                {
                    await Task.Run(() => ssh.Connect());
                }
                catch (SshOperationTimeoutException)
                {
                    return null;
                }
                var settings = (SettingsPageGrid)Frc_ExtensionPackage.Instance.PublicGetDialogPage(typeof(SettingsPageGrid));
                bool verbose = settings.Verbose || settings.DebugMode;
                if (verbose)
                {
                    OutputWriter.Instance.WriteLine($"Running command: {command}");
                }
                return await Task.Run(() => ssh.RunCommand(command));
            }
        }
 public void Startup()
 {
     while (keepstart)
     {
         start = new SshClient(host, user, pass);
         try
         {
             start.Connect();
             start.RunCommand("sudo python3 control/CommandReader.py");
         }
         catch
         {
             Console.Write("not wokring");
         }
     } start.Disconnect();
 }
示例#31
0
    // Use this for initialization
    public void Send()
    {
        string address = "10.211.55.4";
        string user = "******";
        string pass = "******";
        //string cmd = "r2 '/home/parallels/Desktop/Bomb.ex_' -c 'aa;s section..text;afn main;e asm.lines=False;e asm.comments=False;e asm.calls=false;e asm.cmtflgrefs=false;e asm.cmtright=false;e asm.flags=false;e asm.function=false;e asm.functions=false;e asm.vars=false;e asm.xrefs=false;e asm.linesout=false;e asm.fcnlines=false;e asm.fcncalls=false;e asm.demangle=false;aa;s section..text;pdf>main.txt;exit' -q";
        string cmd = "r2 '/home/parallels/Desktop/Bomb.ex_' -c 'aa; s section..text; afn main; pdf @ main > main.txt' -q";
        string uploadfile = @"/Users/JonathanWatts/Desktop/Bomb.ex_";
        string uploadDirectory = "/home/parallels/Desktop/";
        //Upload a file to a linux VM
        using (var sftp = new SftpClient(address, user, pass))
        {
            try
            {
                sftp.Connect();
                using (var fileStream = new FileStream(uploadfile, FileMode.Open))
                {
                    Console.WriteLine("Uploading {0} ({1:N0} bytes)",
                                          uploadfile, fileStream.Length);
                    sftp.BufferSize = 4 * 1024; // bypass Payload error large files
                    sftp.UploadFile(fileStream, uploadDirectory + Path.GetFileName(uploadfile));
                }
                sftp.Disconnect();
                sftp.Dispose();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        //This block of code will send linux terminal commands from windows machine to linux virtual machine
        using(SshClient client = new SshClient(address,user, pass))
        {
            try
            {
                Debug.Log ("Sending Command...");
                client.Connect();
                Debug.Log ("Sending Command...");
                var result = client.RunCommand(cmd);
                Debug.Log (result);
                client.Disconnect();
                Debug.Log ("Sending Command...");
                client.Dispose();
            }
            catch(Exception ex)
            {
                Debug.Log (ex.Message);
                Console.WriteLine(ex.Message);
            }
        }

        //This block of code will download the file from linux VM to the windows host machine
        try
        {
            Debug.Log ("Uploading file...");
            using (var sftp = new SftpClient(address, user, pass))
            {
                sftp.Connect();
                if(File.Exists("/Users/JonathanWatts/main333.txt"))
                {
                    File.Delete("/Users/JonathanWatts/main333.txt");
                }
                using (Stream file1 = File.OpenWrite("/Users/JonathanWatts/main333.txt"))
                {
                    try
                    {

                        sftp.DownloadFile("main.txt", file1);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    file1.Close();

                }
                sftp.Disconnect();
                sftp.Dispose();
            }
        }
        catch(Exception ex)
        {
            Debug.Log (ex.Message);
            Console.WriteLine(ex.Message);
        }

        //SshShell shell = new SshShell(address, user, pass);
    }
示例#32
0
 public object command(object command)
 {
     connect();
     return(_client.RunCommand(command.ToStringOrDefault()));
 }
示例#33
0
        private static object SendCommandToDrone(Drone drone, string commandText)
        {
            using (var ssh = new SshClient(drone.Id, "root", "0953acb"))
            {
                ssh.Connect();
                var cmd = ssh.RunCommand(commandText); //  very long list
                ssh.Disconnect();

                if (cmd.ExitStatus > 0)
                    return new
                    {
                        Drone = drone,
                        Data = cmd.Result.Replace("\n", "<br>")
                    };

                return new
                    {
                        Drone = drone,
                        Data = "OK"
                    };
            }
        }
示例#34
0
文件: MtaAgent.cs 项目: c0d3m0nky/mty
        private string RunCommand(string cmd, Mta pmta)
        {
            if (!_testMode)
            {
                try
                {
                    using (var client = new SshClient(pmta.Host, pmta.Username, pmta.Password))
                    {
                        client.Connect();
                        var command = client.RunCommand(cmd);
                        client.Disconnect();

                        if (command.ExitStatus != 0 && !string.IsNullOrWhiteSpace(command.Error))
                            throw new Exception(string.Format("PMTA Command error: {0}", command.Error));

                        return command.Result;
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("PMTA Command error", e);
                }
            }
            else
            {
                return "";
            }
        }
示例#35
0
        public static void Main(string[] args)
        {
            Console.WriteLine ("Welcome to Brake!");
            Console.WriteLine ("Current version: Brake-0.0.4");
            Container xml = Container.getContainer ();
            if (xml.Config.host == null) {
                xml.Config = new Configuration ();
                Console.Write ("IP address of your iDevice: ");
                xml.Config.host = Console.ReadLine ();
                Console.Write ("SSH Port: ");
                string portString = "22";
                portString = Console.ReadLine ();
                int.TryParse (portString, out xml.Config.port);
                Console.Write ("Root Password: "******"== Is this correct? Y/N ==");
                Console.WriteLine ("Host: " + xml.Config.host);
                Console.WriteLine ("Root Password: "******"y") {
                    return;
                }
                xml.SaveXML ();
            }
            AppHelper appHelper = new AppHelper ();

            //COMING SOON PORT VERIFICATION
            //var ping = new Ping();
            //var reply = ping.Send(host); // 1 minute time out (in ms)
            //if (reply.Status == IPStatus.Success)
            //{
            //    Console.WriteLine("IP Address Valid");
            //}
            //else
            //{
            //    Console.WriteLine("Unable to SSH to IP");
            //}

            Console.WriteLine ("Establishing SSH connection");
            var connectionInfo = new PasswordConnectionInfo (xml.Config.host, xml.Config.port, "root", xml.Config.Password);
            using (var sftp = new SftpClient(connectionInfo)) {
                using (var ssh = new SshClient(connectionInfo)) {
                    ssh.Connect ();
                    sftp.Connect ();
                    var whoami = ssh.RunCommand ("Clutch -b");
                    long b;
                    long.TryParse (whoami.Result, out b);
                    /*if (b < 13104)
                    {
                        Console.WriteLine("You're using an old version of Clutch, please update to 1.3.1!");
                        //COMING SOON download Clutch to device for you
                        //Console.WriteLine("Would you like to download the latest version to your iDevice?");
                        //string dlyn = Console.ReadLine();
                        //if (dlyn == "y")
                        //{
                            //ssh.RunCommand("apt-get install wget");
                            //ssh.RunCommand("wget --no-check-certificate -O Clutch https://github.com/CrackEngine/Clutch/releases/download/1.3.1/Clutch");
                            //ssh.RunCommand("mv Clutch /usr/bin/Clutch");
                            //ssh.RunCommand("chown root:wheel /usr/bin/Clutch");
                            //ssh.RunCommand("chmod 755 /usr/bin/Clutch");
                        //}
                        //else if (dlyn == "Y")
                        //{
                            //ssh.RunCommand("apt-get install wget");
                            //ssh.RunCommand("wget --no-check-certificate -O Clutch https://github.com/CrackEngine/Clutch/releases/download/1.3.1/Clutch");
                            //ssh.RunCommand("mv Clutch /usr/bin/Clutch");
                            //ssh.RunCommand("chown root:wheel /usr/bin/Clutch");
                            //ssh.RunCommand("chmod 755 /usr/bin/Clutch");
                        //}
                        //else
                        //{
                            return;
                        //}
                    }*/
                    Console.WriteLine ("reply: " + whoami.Result);

                    //return;
                    string location;
                    switch (RunningPlatform ()) {
                    case Platform.Mac:
                        {
                            location = Environment.GetEnvironmentVariable ("HOME") + "/Music/iTunes/iTunes Media/Mobile Applications";
                            break;
                        }
                    case Platform.Windows:
                        {
                            string location2 = Environment.GetFolderPath (Environment.SpecialFolder.MyMusic);
                            location = Path.Combine (location2, "iTunes\\iTunes Media\\Mobile Applications");
                            break;
                        }
                    default:
                        {
                            Console.WriteLine ("Unknown operating system!");
                            return;
                        }
                    }
                    appHelper.getIPAs (location);
                    int i = 1;
                    int a;
                    while (true) {
                        foreach (IPAInfo ipaInfo in xml.IPAItems) {
                            Console.WriteLine (i + ". >> " + ipaInfo.AppName + " (" + ipaInfo.AppVersion + ")");
                            i++;
                        }
                        Console.WriteLine ("");
                        Console.Write ("Please enter your selection:  ");
                        if (int.TryParse (Console.ReadLine (), out a)) {
                            try {
                                IPAInfo ipaInfo = xml.IPAItems [a - 1];
                                Console.WriteLine ("Cracking " + ipaInfo.AppName);
                                String ipalocation = appHelper.extractIPA (ipaInfo);

                                using (var file = File.OpenRead(ipalocation)) {
                                    Console.WriteLine ("Uploading IPA to device..");
                                    sftp.UploadFile (file, "Upload.ipa");

                                }

                                Console.WriteLine ("Cracking! (This might take a while)");
                                String binaryLocation = ipaInfo.BinaryLocation.Replace ("Payload/", "");
                                String TempDownloadBinary = Path.Combine (AppHelper.GetTemporaryDirectory (), "crackedBinary");
                                var crack = ssh.RunCommand ("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                                Console.WriteLine ("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                                Console.WriteLine ("cracking output: " + crack.Result);

                                using (var file = File.OpenWrite(TempDownloadBinary)) {
                                    Console.WriteLine ("Downloading cracked binary..");
                                    sftp.DownloadFile ("/tmp/crackedBinary", file);
                                }

                                String repack = appHelper.repack (ipaInfo, TempDownloadBinary);
                                Console.WriteLine ("Cracking completed, file at " + repack);
                            } catch (IndexOutOfRangeException) {
                                Console.WriteLine ("Invalid input, out of range");
                                return;
                            }
                        } else {
                            Console.WriteLine ("Invalid input");
                            return;
                        }

                        AppHelper.DeleteDirectory (AppHelper.GetTemporaryDirectory ());
                        sftp.Disconnect ();
                    }
                }
            }
        }
示例#36
0
 private void numericUpDown1_ValueChanged(object sender, EventArgs e)
 {
     if (connected == true)
     {
         SshCommand x = cSSH.RunCommand("media vol" + volumeControl.Value.ToString());
         printInfo("Volume changed to: " + volumeControl.Value.ToString());
     }
 }
示例#37
0
 public bool ExecuteScript(Server server, string script)
 {
     using (SshClient cSSH = new SshClient(server.Uri, server.Port.Value, server.UserName, server.Password))
     {
         cSSH.Connect();
         var commands = script.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
         foreach (var command in commands)
         {
             SshCommand x = cSSH.RunCommand(command);
             var reader = new StreamReader(x.OutputStream);
             string output = reader.ReadToEnd();
             Console.WriteLine("$:" + output);
         }
         cSSH.Disconnect();
     }
     return true;
 }
示例#38
0
        private static void updateProject(SshClient client)
        {
            ConsoleLogStartAction(Resources.UILogging.UpdateSVN);

            var userName = ConfigurationManager.AppSettings[AppSettingKeys.SVNUserName];

            if (userName.isNullOrEmpty())
            {
                Console.WriteLine(Resources.Questions.SVNUser);
                userName = Console.ReadLine();
            }

            Console.WriteLine(Resources.Questions.SVNPassword);
            using (SecureString password = GetPassword())
            {
                client.RunCommand(string.Format(Program.SVNCommand, userName, password.ConvertToUnsecureString()));
            }

            ConsoleEndAction();
        }
        public static async Task<Dictionary<string, SshCommand>> RunCommands(string[] commands, ConnectionUser user)
        {
            ConnectionInfo connectionInfo;
            switch (user)
            {
                case ConnectionUser.Admin:
                    connectionInfo = s_adminConnectionInfo;
                    break;
                case ConnectionUser.LvUser:
                    connectionInfo = s_lvUserConnectionInfo;
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(user), user, null);
            }

            Dictionary<string, SshCommand> retCommands = new Dictionary<string, SshCommand>();
            using (SshClient ssh = new SshClient(connectionInfo))
            {
                try
                {
                    await Task.Run(() => ssh.Connect());
                }
                catch (SshOperationTimeoutException)
                {
                    return null;
                }
                var settings = (SettingsPageGrid)Frc_ExtensionPackage.Instance.PublicGetDialogPage(typeof(SettingsPageGrid));
                bool verbose = settings.Verbose || settings.DebugMode;
                foreach (string s in commands)
                {
                    if (verbose)
                    {
                        OutputWriter.Instance.WriteLine($"Running command: {s}");
                    }
                    await Task.Run(() =>
                    {
                        var x = ssh.RunCommand(s);

                        retCommands.Add(s, x);
                    });
                }
            }
            return retCommands;
        }
示例#40
-1
        static void Main(string[] args)
        {
            string address = "192.168.17.129";
            string user = "******";
            string pass = "******";
            string cmd = "r2 '/home/swastik/Desktop/Bomb.ex_' -c 'aa;s section..text;pdf;pdi;e asm.lines=False;e asm.comments=False;e asm.calls=false;e asm.cmtflgrefs=fal;e asm.cmtright=false;e asm.flags=false;e asm.function=false;e asm.functions=fals;e asm.vars=false;e asm.xrefs=false;e asm.linesout=false;e asm.fcnlines=false;e asm.fcncalls=false;e asm.demangle=false;aa;s section..text;pdf>main.txt;exit' -q";
            string uploadfile = @"C:\Users\Swastik\Google Drive\Research\Malaware Visualization\Tool\radare2-w32-0.9.9-git\Bomb.ex_";
            string uploadDirectory = "/home/swastik/Desktop/";
            //Upload a file to a linux VM
            using (var sftp = new SftpClient(address, user, pass))
            {
                try
                {
                    sftp.Connect();
                    using (var fileStream = new FileStream(uploadfile, FileMode.Open))
                    {
                        Console.WriteLine("Uploading {0} ({1:N0} bytes)",
                                            uploadfile, fileStream.Length);
                        sftp.BufferSize = 4 * 1024; // bypass Payload error large files
                        sftp.UploadFile(fileStream, uploadDirectory + Path.GetFileName(uploadfile));
                    }
                    sftp.Disconnect();
                    sftp.Dispose();
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            //This block of code will send linux terminal commands from windows machine to linux virtual machine
            using(SshClient client = new SshClient(address,user, pass))
            {
                try
                {
                    client.Connect();
                    var result = client.RunCommand(cmd);
                    client.Disconnect();
                    client.Dispose();
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            //This block of code will download the file from linux VM to the windows host machine
            try
            {
                using (var sftp = new SftpClient(address, user, pass))
                {
                    sftp.Connect();
                    using (Stream file1 = File.OpenWrite("d:\\main333.txt"))
                    {
                        try
                        {

                            sftp.DownloadFile("main.txt", file1);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        file1.Close();

                    }
                    sftp.Disconnect();
                    sftp.Dispose();
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //SshShell shell = new SshShell(address, user, pass);
        }