看板 Python 關於我們 聯絡資訊
小弟是使用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://www.ptt.cc/bbs/Python/M.1533281921.A.46E.html ※ 編輯: phoenixcx (203.75.55.2), 08/03/2018 15:39:05
s860134: 使用 interactive shell 08/03 19:34
s860134: exec command 屬於 ssh 原生功能 行為上和一般 shell 還 08/03 19:35
s860134: 是有差 08/03 19:35
kenduest: 你可以想一下,手動 ssh root@hostname "su -l games" 08/03 19:42
kenduest: 一定也是處於卡住的狀態,因為後續進入 shell 的 08/03 19:42
kenduest: login 互動 shell 了,所以變成後續 shell 沒有返回 08/03 19:43
kenduest: exec_command 是執行某個命令要等返回才有結果 08/03 19:44
kenduest: 所以改成一次跑完結束返回就好. su - james -c whoami 08/03 19:45
kenduest: 若你要能夠 ssh 登入,後續互動模式執行命令 08/03 19:47
kenduest: 用 Pexpect 搭配 pxssh 來處理應該比較方便 08/03 19:48
s860134: shell = ssh.invoke_shell() 08/03 21:22
s860134: 之後只要使用 shell.send shell.recv 就可以滿足你要的 08/03 21:22
s860134: 任何功能惹 08/03 21:22
s860134: 順便提一下 exec_command 下的 env 沒執行過 08/03 21:24
s860134: /etc/profile 所以尤其是 PATH 會跟你常用的不大一樣 08/03 21:24
s860134: 相對 invoke_shell 下面的 env 會正常一點 08/03 21:26
phoenixcx: 感謝各位大大 禮拜一試一下 08/04 22:16