我對Paramiko的工作原理相當陌生,但我的主要目標是能夠使用Python通過SSH運行自動命令。Python:Paramiko在嘗試通過SSH執行命令時掛起
我有以下代碼,我試圖運行一個簡單的ls
命令開始,但由於某種奇怪的原因代碼似乎卡住,沒有輸出或錯誤消息產生。
import sys
import paramiko as pm
sys.stderr = sys.__stderr__
import os
class AllowAllKeys(pm.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
return
HOST = '192.168.31.1'
USER = 'admin'
PASSWORD = 'admin'
client = pm.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(pm.AutoAddPolicy())
client.connect(HOST, username=USER, password=PASSWORD)
channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')
stdin.write('''
ls
exit
''')
print stdout.read()
stdout.close()
stdin.close()
任何幫助,將不勝感激:)
確定'stdin'和'stdout'不倒? – Elazar
@ mrpopo,更好的,你可以使用pexpect模塊,而不是paramiko – abhi
我想最初使用pexpect,但我使用的是Windows機器:/ 無法在Windows上導入資源。不用擔心,我只會虛擬一個debian客戶端並學習pexpect。 – mrpopo