2014-09-30 81 views
0

執行reboot命令通過SSH我使用Paramiko建立一些目標設備的SSH連接,我想執行reboot命令。使用的paramiko

ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect(zip_hostname, username=username, password=password, timeout=1) 
try: 
    stdin, stdout, stderr = ssh.exec_command("/sbin/reboot -f") 
    # ......... 
    # some code 
    # ......... 
except AuthenticationException, e: 
    print '' 
finally: 
    ssh.close() 

但在執行ssh.exec_command("/sbin/reboot -f")後「一些代碼」不執行,因爲程序是停留在exec_command(斷線發生造成重新啓動的地方)。我該怎麼做才能解決我的問題?

回答

3

試試這個:

ssh.exec_command("/sbin/reboot -f > /dev/null 2>&1 &") 

所有重啓的輸出重定向到/ dev/null的,使其不產生輸出,它是後臺感謝到底「&」標誌的開始。希望程序不會像這樣掛在那條線上,因爲遠程shell會提示回來。

1

獲取從SSH運輸和使用設置的存活時間:

transport = ssh.get_transport() 
transport.set_keepalive(5) 

sets the keepalive5秒;請注意,我本來預計timeout=1已達到同樣的效果。

0

所有你需要做的就是調用channel.exec_command()而不是高層接口的client.exec_command()

# exec fire and forget 
timeout=0.5 
transport = ssh.get_transport() 
chan = ssh.get_transport().open_session(timeout=timeout) 
chan.settimeout(timeout) 
try: 
    chan.exec_command(command) 
except socket.timeout: 
    pass