作者phoenixcx (曼秀雷敦)
看板Python
标题[问题] 请问paramiko如何切换使用者
时间Fri Aug 3 15:38:37 2018
小弟是使用python3
目前有两个环境 一个是用root登入,另外是只能用一般使用者登入
如何用root登入後切换一般使用者
或是一般使用者登入切换成root?
感谢
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip,port=22,username='root',password=pw,timeout=5)
stdin, stdout, stderr = ssh.exec_command('su - james')
stdin, stdout, stderr = ssh.exec_command('whoami')
print(stdout.readlines())
ssh.close()
目前这样写会卡死无回应
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 203.75.55.2
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1533281921.A.46E.html
※ 编辑: phoenixcx (203.75.55.2), 08/03/2018 15:39:05
1F:推 s860134: 使用 interactive shell 08/03 19:34
2F:→ s860134: exec command 属於 ssh 原生功能 行为上和一般 shell 还 08/03 19:35
3F:→ s860134: 是有差 08/03 19:35
4F:→ kenduest: 你可以想一下,手动 ssh root@hostname "su -l games" 08/03 19:42
5F:→ kenduest: 一定也是处於卡住的状态,因为後续进入 shell 的 08/03 19:42
6F:→ kenduest: login 互动 shell 了,所以变成後续 shell 没有返回 08/03 19:43
7F:→ kenduest: exec_command 是执行某个命令要等返回才有结果 08/03 19:44
8F:→ kenduest: 所以改成一次跑完结束返回就好. su - james -c whoami 08/03 19:45
9F:→ kenduest: 若你要能够 ssh 登入,後续互动模式执行命令 08/03 19:47
10F:→ kenduest: 用 Pexpect 搭配 pxssh 来处理应该比较方便 08/03 19:48
11F:→ s860134: shell = ssh.invoke_shell() 08/03 21:22
12F:→ s860134: 之後只要使用 shell.send shell.recv 就可以满足你要的 08/03 21:22
13F:→ s860134: 任何功能惹 08/03 21:22
14F:→ s860134: 顺便提一下 exec_command 下的 env 没执行过 08/03 21:24
15F:→ s860134: /etc/profile 所以尤其是 PATH 会跟你常用的不大一样 08/03 21:24
16F:→ s860134: 相对 invoke_shell 下面的 env 会正常一点 08/03 21:26
17F:→ phoenixcx: 感谢各位大大 礼拜一试一下 08/04 22:16