作者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/m.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