我正试图加速Paramiko SSH与几个网络设备的连接。我想为此目的使用异步,但我不确定我对它的实现是否正确,因为我没有看到执行时间有任何好处,如果我们不使用它,脚本每次执行大约6s。其想法是,第二个主机启动其SSH连接,而无需等待第一个主机的SSH连接的建立。
下面是我的当前代码,它运行但没有产生任何好处。任何建议,如何使它工作或改进,如果这是可能的,在这里。
import paramiko
import time
import asyncio
async def sshTest(ipaddress,deviceUsername,devicePassword,sshPort): #finalDict
try:
print("Performing SSH Connection to the device")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ipaddress, username=deviceUsername, password=devicePassword, port=sshPort, look_for_keys=False, allow_agent=False)
print("Channel established")
except Exception as e:
print(e)
async def main():
print("Session 1 \n")
await sshTest('192.168.255.11','admin','admin','22')
print("Session 2 \n")
await sshTest('192.168.254.11','admin','admin','22')
if __name__ == "__main__":
start = time.time()
asyncio.run(main())
end = time.time()
print("The time of execution of above program is :", end-start)
发布于 2022-03-17 08:18:17
如果要异步执行此任务,请创建任务列表并将每个异步任务添加到该列表中。使用await asyncio.gather(*tasks)
,您的函数使用I/O绑定异步执行任务。
编辑关于@satman的评论,我添加了一个asyncssh
函数,而不是paramiko
#import paramiko
import asyncssh
import time
import asyncio
async def sshTest(ipaddress,deviceUsername,devicePassword,sshPort): #finalDict
try:
print("Performing SSH Connection to the device")
#client = paramiko.SSHClient()
#client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#client.connect(ipaddress, username=deviceUsername, password=devicePassword, port=sshPort, look_for_keys=False, allow_agent=False)
async with asyncssh.connect(ipaddress, username=deviceUsername, password=devicePassword, known_hosts=None) as conn:
async with conn.start_sftp_client() as sftp:
#Here you can enter the commands you want to execute, e.g. import data from a device
await sftp.get("folder_device", "folder_local", preserve=True, recurse=True)
print("Channel established")
except Exception as e:
print(e)
async def main():
start = time.time()
ip_list = ['192.168.254.11','192.168.255.11']
tasks = []
for ip in ip_list:
tasks.append(asyncio.create_task(sshTest(ip,'admin','admin','22')))
await asyncio.gather(*tasks)
end = time.time()
print("The time of execution of above program is :", end-start)
if __name__ == "__main__":
asyncio.run(main())
发布于 2022-07-29 07:56:47
您能像上面建议的那样异步使用paramiko吗?只有一个线程,如果paramiko阻塞,它将不会将控制权转移到另一个任务,我认为。库也需要异步设计,不是吗?因此,如果您想要异步ssh连接,您必须使用异步ssh。
https://stackoverflow.com/questions/71169287
复制相似问题