使用Paramiko的SSH客户端

2 投票
1 回答
2914 浏览
提问于 2025-04-16 17:29
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连接呢?

1 个回答

1

如果我理解得没错的话,你应该在你的代码中加上类似这样的内容:

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.

撰写回答