Sudo Command in the C# SSH .Net library

14,540
        public void ExpectSSH (string address, string login, string password, string command)
    {
        try
        {
            SshClient sshClient = new SshClient(address, 22, login, password);

            sshClient.Connect();
            IDictionary<Renci.SshNet.Common.TerminalModes, uint> termkvp = new Dictionary<Renci.SshNet.Common.TerminalModes, uint>();
            termkvp.Add(Renci.SshNet.Common.TerminalModes.ECHO, 53);

            ShellStream shellStream = sshClient.CreateShellStream("xterm", 80,24, 800, 600, 1024, termkvp);


            //Get logged in
            string rep = shellStream.Expect(new Regex(@"[$>]")); //expect user prompt
            this.writeOutput(results, rep);

            //send command
            shellStream.WriteLine(commandTxt.Text);
            rep = shellStream.Expect(new Regex(@"([$#>:])")); //expect password or user prompt
            this.writeOutput(results, rep);

            //check to send password
            if (rep.Contains(":"))
            {
                //send password
                shellStream.WriteLine(password);
                rep = shellStream.Expect(new Regex(@"[$#>]")); //expect user or root prompt
                this.writeOutput(results, rep);
            }

            sshClient.Disconnect();      
        }//try to open connection
        catch (Exception ex)
        {
            System.Console.WriteLine(ex.ToString());
            throw ex;
        }

    }
Share:
14,540
Nicholas Smith
Author by

Nicholas Smith

Updated on June 24, 2022

Comments

  • Nicholas Smith
    Nicholas Smith almost 2 years

    This is the simplest sudo implementation of the SSH .Net library I can find. However, I can not get it to work.

        using (var ssh = new SshClient("hostname", "username", "password"))
            {
                ssh.Connect();
                var input = new MemoryStream();
                var sr = new StreamWriter(input);
                var output = Console.OpenStandardOutput();
    
                var shell = ssh.CreateShell(input, output, output);
                shell.Stopped += delegate
                {
                    Console.WriteLine("\nDisconnected...");
                };
    
                shell.Start();
                sr.WriteLine("sudo ls");
                sr.Flush();
                Thread.Sleep(1000 * 1);
                sr.WriteLine("password");
                sr.Flush();
                Thread.Sleep(1000 * 100);
                shell.Stop();
            }
    

    I get the following error everytime

    last login: Wed Jan 14 15:51:46 2015 from mycomputer


    company stuff


    SshNet.Logging Verbose: 1 : ReceiveMessage from server: 'ChannelDataMessage': 'SSH_MSG_CHANNEL_DATA : #0'. SshNet.Logging Verbose: 1 : ReceiveMessage from server: 'ChannelDataMessage': 'SSH_MSG_CHANNEL_DATA : #0'. [1;36mThis is BASH [1;31m4.1[1;36m- DISPLAY on [1;31m:0.0[m

    Wed Jan 14 15:55:50 CST 2015 SshNet.Logging Verbose: 1 : ReceiveMessage from server: 'ChannelDataMessage': 'SSH_MSG_CHANNEL_DATA : #0'. SshNet.Logging Verbose: 1 : ReceiveMessage from server: 'ChannelDataMessage': 'SSH_MSG_CHANNEL_DATA : #0'. -bash: And,: command not found [0;34musername@host [0;31m[15:55:50]>[0m

  • Nicholas Smith
    Nicholas Smith over 9 years
    This is posted in case anyone else runs into this issue. It is a very simple example of how expect can be used with the ssh .net library. It actually works very well. However, I haven't add AIX or Solaris support into the expect. Furthermore, some daily server messages could break the expect regex.
  • redspidermkv
    redspidermkv over 8 years
    Thanks for posting a working example. I haven't tried the original code but did you ever figure out why it wasn't working?
  • Admin
    Admin over 8 years
    how do you know when the command finished executing, in case say you do ls -R /, that might take quite a bit of time, is there a way to synchronize based on that?
  • Alkampfer
    Alkampfer about 8 years
    I've tried to use the code above, but always gives me "wrong password". I've tried shellStream.Write(password + "\n") or shellStream.Write(password + "\r") also, with no luck.
  • Zakos
    Zakos over 7 years
    who is "this" ?
  • jmistx
    jmistx over 6 years
    I believe this is the original source for this answer with some information. refactoragain.com/2016/05/27/ssh-net-echo-sudo-s
  • HeavyHead
    HeavyHead over 6 years
    Note you can pipe the sudo command with the password directly in one line. I had trouble in my code when being prompted for the password and responding. I found a work around like so; "sudo -S <<< password" hope this is useful, I've spent three days faffing about with various codes and examples :/