Executing command using “su -l” in SSH using Python

General disclaimers first (to others who stumble upon this question):


If none of the above is feasible (and you really tried hard to make the admin enable some of the options above):

As the last resort option, you can write the command to a standard input of the su, the same way you already write a password (another thing not to do):

stdin, stdout, stderr = session.exec_command("su -l " + user_to_log)

stdin.write(password_to_log + '\n')
stdin.flush()

command = 'whoami'
stdin.write(command + '\n')
stdin.flush()

(also note that it’s redundant to call makefile, as exec_command already returns that)

See Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko.


Note that your question is not about which SSH client library to use. It does not matter if you use Paramiko or other. This all is actually a generic SSH/Linux/shell question.

Leave a Comment