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

标签 python shell ssh paramiko su

我需要通过 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 身份而不是以 foo 身份执行 pwd。

怎么了?

最佳答案

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

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

关于python - 在 paramiko ssh 连接上执行 su 用户(无密码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8418026/

相关文章:

linux - $() 与重定向有何不同?

regex - 如何使用正则表达式从 html 文档中提取特定的元信息

ruby - 在多个 SSH 隧道上运行 MySQL 查询?

git - Windows VS Code 能否在连接到 git 存储库的 Ubuntu 主机上通过 ssh 运行 git 命令

linux - 特定机器拒绝 ssh 登录权限

python - Mongo引擎查询引用字段

python - WRF 兰伯特等角圆锥曲线如何转换为纬度/经度绘图偏移

shell - 如何定期保存程序输出的最后一行?

python - mysql 查询过滤器 LIKE 无法正常工作

Python:如何将区域保持在 canny close edge 的区域内