2

我需要在 ssh 中登录到服务器,执行“su 用户名”(无密码)以作为该用户执行一些命令(在 ssh 中没有直接登录)。

从终端它会是这样的:

root@cs01:~# su foo
foo@cs01:/root$ cd
foo@cs01:~$ ls

我试图用 paramiko (python) 来做到这一点:

import paramiko
ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('host', username='root', password='mypassword', key_filename='<filename>')

stdin, stdout, stderr = ssh.exec_command('su foo')
print stdout.readlines()
stdin, stdout, stderr = ssh.exec_command('cd')
print stdout.readlines()
stdin, stdout, stderr = ssh.exec_command('pwd')
print stdout.readlines()
ssh.close()

但剧本并没有结束。

日志是这些:

...
DEB [20111207-16:22:25.538] thr=1   paramiko.transport: userauth is OK
INF [20111207-16:22:25.921] thr=1   paramiko.transport: Authentication (publickey) successful!
DEB [20111207-16:22:25.923] thr=2   paramiko.transport: [chan 1] Max packet in: 34816 bytes
DEB [20111207-16:22:26.088] thr=1   paramiko.transport: [chan 1] Max packet out: 32768 bytes
INF [20111207-16:22:26.088] thr=1   paramiko.transport: Secsh channel 1 opened.
DEB [20111207-16:22:26.151] thr=1   paramiko.transport: [chan 1] Sesch channel 1 request ok

如果我只尝试这个:

stdin, stdout, stderr = ssh.exec_command('su foo')
#without print
stdin, stdout, stderr = ssh.exec_command('pwd')
print stdout.readlines()

它以 root 身份执行 pwd,而不是 foo。

怎么了?

4

1 回答 1

8

每个exec_command()调用都发生在一个新的 shell 中,因此没有从以前的命令继承的状态。如果命令依赖于先前的命令来执行,则必须在单个语句中或作为脚本发送它们。如果你想要一个交互式shell,有invoke_shell命令,但是你需要解析shell输出来模拟交互式使用(这里可以使用pexpect库)。

您可以使用该sudo命令,或su -c执行该命令。但是,我建议为所需用户配置安全登录,并直接以该用户身份连接。

于 2011-12-07T15:57:07.117 回答