sudo su SSH in C# using ShellStream

All,

Im trying to use an ssh library within .NET to be able to connect to a database to run a shell script. In order to do that, I must sudo -su as another user that has the deprives to do that. Im unable to bypass the password input portion of the process. Am I typing out the Regex Expect correctly?

In Putty, Immediately after logging in the first prompt looks like this: [chungb@ite-mup-sys-db ~]$

In Putty, the prompt when asking for the password after typing the command (sudo su - payrun) looks like this: [sudo] password for chungb:

SshClient client = new SshClient(ip, 22, login, pw);
client.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 =
         client.CreateShellStream("xterm", 80, 24, 800, 600, 1024, termkvp);

var output = shellStream.Expect(new Regex(@"[\[chungb@ite-mup-sys-db ~]$]"));

shellStream.WriteLine("sudo su - payrun");
output = shellStream.Expect(new Regex(@"[\[sudo] password for chungb:"));
shellStream.WriteLine(pw);


client.Disconnect();

1 answer

  • answered 2018-01-11 21:25 Drasz

    If you have access to the server, you could avoid typing a password by configuring sudo to grant you access to this specific command:

    username ALL=(ALL) NOPASSWD: /path/to/mycommand
    

    This assumes a username of "username" and your command to reside at /path/to/mycommand.

    IF you really must provide the password in the code, which is highly insecure and not advisable in any scenario, you could try it like this:

    echo "password" | sudo -S /path/to/mycommand