'asyncio and paramiko for concurrent ssh connectivity

I'm trying to speed up the Paramiko SSH connection to a couple of network devices. I want to use asyncio for that purpose, but I'm not sure if my implementation of it is correct, as I don't see any benefit in execution time, with our without using it, the scripts executes for around 6s each time. The idea was, for he second host to start the its SSH connection without waiting for the SSH connection of the first host to be established.

Here is my current code, which runs but doesn't produce any benefit. Any suggestion how to make it work or improve, if that is possible here.

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)


Solution 1:[1]

If you want to execute this task asynchronously, create a task list and add each asyncio task to that list. With await asyncio.gather(*tasks) your function executes the task asynchronously with an I/O binding.

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():
    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())
   

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1