1
votes

I am using Paramiko to do the standard SSH into a box, run commands, and display the STDOUT to my terminal. Due to sudo rules, I SSH into a machine with my username and run sudo /bin/su -s /bin/bash - <diff user account>. In my script, I am passing the following command into Paramiko but the STDOUT does not show on my screen. I believe this is because the sudo command is opening a new shell and Paramiko is watching the STDOUT on the new shell.

The commands DO run as I have logged onto the box and see the command history. How do I get the STDOUT of the commands I am running to show on my terminal?

import paramiko

def sshCommand(hostname, port, username, command, key_filename='/home/<my username>/.ssh/id_rsa'):
        sshClient = paramiko.SSHClient()
        sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        sshClient.connect(hostname=hostname, port=port, username=username, key_filename=key_filename)
        stdin, stdout, stderr = sshClient.exec_command(command, get_pty=False)
        output = stdout.readlines()
        print(output)

sshCommand('<servername>', 22, '<my username>', """sudo /bin/su -s /bin/bash - <diff username> << \'EOF\'
echo "Hello World"
EOF
""")
1
Does it work with a simpler command, like sudo /bin/su -s /bin/bash - username echo foo? - Martin Prikryl
Nope. but from the server itself it does. I am looking in to the "invoke_shell" function for paramiko to see if that may work invoke_shell(*args, **kwds) Request an interactive shell session on this channel. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the shell. - bYt34byt3
We need minimal reproducible example - so please reduce your code to the simplest example that still reproduces your problem. - Martin Prikryl
Just reduced my code to the simplest example. - bYt34byt3
Does it work, if you specify the command directly on su command-line (not via a redirected input)? - Martin Prikryl

1 Answers

0
votes

I do not think that OpenSSH SSH server can accept the << 'EOF' shell construct on the "exec" channel.

But this should work:

echo echo "Hello World" | sudo /bin/su -s /bin/bash - <diff username>