Skip to main content
 首页 » 编程设计

python之带有 paramiko 的 ssh 客户端

2025年05月04日7zengkefu

import paramiko 
import os 
 
def connection(): 
    ssh = paramiko.SSHClient() 
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    privatekey = os.path.expanduser('/home/rabia/private') 
    mkey = paramiko.RSAKey.from_private_key_file(privatekey) 
    ssh.connect('78.46.172.47', port=22, username='s0urd', password=None, pkey=mkey) 
    stdin, stdout, stderr = ssh.exec_command('ls') 
    print stdout.readlines() 
 
connection() 

如何让一个线程等待用户输入而另一个线程进行 ssh 连接?

请您参考如下方法:

如果我对你的理解正确,那么你应该在你的代码中添加这样的东西:

import threading 
 
_paramikoThread = threading.Thread(target=doParamikoConnection) 
_paramikoThread.start() 
# The following code is executed by parent thread. 
_ans = "" 
while _ans != "nay": 
    _ans = raw_input("Should I loop again? [yay/nay]") 
# Now we've ended user I/O session, wait for connection to complete. 
_paramikoThread.join() 
# At this point we have data collected from user and connection being initialised.