简体   繁体   中英

Providing input to command (su) executed using Python Paramiko Transport class due to special authentication needs

I use Paramiko to connect with my unix host with goal to execute the the following commands:

  1. whoami --> This will print PAM functional account
  2. hostname --> hostname of the unix server
  3. sudo su(for sudo no password is required, it automatically takes to root user) --> This will take it to root user
  4. whoami --> this should print root

The #1 and #2 commands works fine and in the stdout response can see the expected result.

trans.auth_interactive(username='username', handler=handler)
session = trans.open_session()
stdout_data = None
stderr_data = None

(stdin, stdout, stderr) = session.exec_command("sudo su -")

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

result = stdout.readlines()
print(result)
output = str(result)
print(output)
print_hi('done')

Console logs

INFO:paramiko.transport:Authentication (keyboard-interactive) successful!
DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 0] Max packet out: 32768 bytes
DEBUG:paramiko.transport:Secsh channel 0 opened.
DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok
Traceback (most recent call last):
  File "C:/Users/tpukrisi/PycharmProjects/Paramiko/paramikoppam.py", line 77, in <module>
    connect_pam_host()
  File "C:/Users/tpukrisi/PycharmProjects/Paramiko/paramikoppam.py", line 21, in connect_pam_host
    (stdin, stdout, stderr) = session.exec_command("sudo su -")
TypeError: cannot unpack non-iterable NoneType object
DEBUG:paramiko.transport:EOF in transport thread

Process finished with exit code 1

Thanks Krishna

The low-level Channel.exec_command does not return anything (unlike the high-level SSHClient.exec_command ).

If you want to obtain the I/O, you have to call Channel 's makefile* methods.

This is simplified code of what SSHClient.exec_command does internally:

chan = transport.open_session()
chan.exec_command(command)
stdin = chan.makefile_stdin("wb", bufsize)
stdout = chan.makefile("r", bufsize)
stderr = chan.makefile_stderr("r", bufsize)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM