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

前端 未结 1 1047
小蘑菇
小蘑菇 2020-11-30 13:41

I use a friends server that allows only one user to be logged from SSH, so normally I just log in as that user and then do su -l myuser to change accounts. I wa

相关标签:
1条回答
  • 2020-11-30 14:04

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

    • Using su is not the right solution. su is a tool intended for an interactive use, not for an automation. The correct solution is to login with the correct account directly.

      Or at at least use a password-less sudo.

      Or you can create a root-owner script with setuid right.

      See also Allowing automatic command execution as root on Linux using SSH.

    • If you are stuck with su, on most systems you can use -c switch to su to specify a command:

      su -c "whoami" user
      

      See also How to run sudo with paramiko? (Python)


    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 general SSH/shell question.

    0 讨论(0)
提交回复
热议问题