Python 在paramiko ssh连接上执行su用户(无密码)

Python 在paramiko ssh连接上执行su用户(无密码),python,shell,ssh,paramiko,su,Python,Shell,Ssh,Paramiko,Su,我需要在ssh中登录到服务器,执行“su username”(无密码)以作为该用户执行一些命令(在ssh中没有直接登录) 从终端上看,可能是这样的: root@cs01:~# su foo foo@cs01:/root$ cd foo@cs01:~$ ls 我曾尝试使用paramiko(python)实现这一点: 如果我只尝试这个: stdin, stdout, stderr = ssh.exec_command('su foo') #without print stdin, stdout,

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

从终端上看,可能是这样的:

root@cs01:~# su foo
foo@cs01:/root$ cd
foo@cs01:~$ ls
我曾尝试使用paramiko(python)实现这一点:

如果我只尝试这个:

stdin, stdout, stderr = ssh.exec_command('su foo')
#without print
stdin, stdout, stderr = ssh.exec_command('pwd')
print stdout.readlines()
它以root而不是foo的形式执行pwd

怎么了?

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


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

thx。我的目标是给su用户打电话,然后是cd(去他的家),然后是svn。有一种方法可以连接这个,或者连接到paramiko中的mantain状态?
su foo-c“svn up/home/foo”
是一种可能性。首先在命令行上编写脚本,因为这与paramiko无关。并不是说你不能在paramiko中“维护状态”,而是你在执行两个独立的shell。
...
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()