[問題] 請問paramiko如何切換使用者

看板Python作者 (曼秀雷敦)時間7年前 (2018/08/03 15:38), 7年前編輯推噓1(1016)
留言17則, 3人參與, 7年前最新討論串1/1
小弟是使用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

08/03 19:34, 7年前 , 1F
使用 interactive shell
08/03 19:34, 1F

08/03 19:35, 7年前 , 2F
exec command 屬於 ssh 原生功能 行為上和一般 shell 還
08/03 19:35, 2F

08/03 19:35, 7年前 , 3F
是有差
08/03 19:35, 3F

08/03 19:42, 7年前 , 4F
你可以想一下,手動 ssh root@hostname "su -l games"
08/03 19:42, 4F

08/03 19:42, 7年前 , 5F
一定也是處於卡住的狀態,因為後續進入 shell 的
08/03 19:42, 5F

08/03 19:43, 7年前 , 6F
login 互動 shell 了,所以變成後續 shell 沒有返回
08/03 19:43, 6F

08/03 19:44, 7年前 , 7F
exec_command 是執行某個命令要等返回才有結果
08/03 19:44, 7F

08/03 19:45, 7年前 , 8F
所以改成一次跑完結束返回就好. su - james -c whoami
08/03 19:45, 8F

08/03 19:47, 7年前 , 9F
若你要能夠 ssh 登入,後續互動模式執行命令
08/03 19:47, 9F

08/03 19:48, 7年前 , 10F
用 Pexpect 搭配 pxssh 來處理應該比較方便
08/03 19:48, 10F

08/03 21:22, 7年前 , 11F
shell = ssh.invoke_shell()
08/03 21:22, 11F

08/03 21:22, 7年前 , 12F
之後只要使用 shell.send shell.recv 就可以滿足你要的
08/03 21:22, 12F

08/03 21:22, 7年前 , 13F
任何功能惹
08/03 21:22, 13F

08/03 21:24, 7年前 , 14F
順便提一下 exec_command 下的 env 沒執行過
08/03 21:24, 14F

08/03 21:24, 7年前 , 15F
/etc/profile 所以尤其是 PATH 會跟你常用的不大一樣
08/03 21:24, 15F

08/03 21:26, 7年前 , 16F
相對 invoke_shell 下面的 env 會正常一點
08/03 21:26, 16F

08/04 22:16, 7年前 , 17F
感謝各位大大 禮拜一試一下
08/04 22:16, 17F
文章代碼(AID): #1RP0Q1Hk (Python)
文章代碼(AID): #1RP0Q1Hk (Python)