Search code examples
pythonsshparallel-ssh

How to connect to multiple servers through ssh with different hosts & passwords in python?


How to connect to multiple servers through ssh with different hosts & passwords in python?

I've tried to use Parallel-ssh. But I was unable to connect to multiple servers that had a different password.

Example from there documentation for a single server:

from pssh.clients import ParallelSSHClient

hosts = ['host1', 'host2', 'host3']

client = ParallelSSHClient(hosts, user='my_user', password='my_pass')

Solution

  • You might be interested in fabric. It provides similar functionality, but also allows you to manually create each connection and then pass them into a group. For example:

    from fabric.connection import Connection
    from fabric.group import SerialGroup, ThreadingGroup
    
    config = {
        'host1': {'password': '...'},
        'host2': {'password': '...'},
    }
    
    connections = []
    for hostname, parameters in config.items():
        conn = Connection(host=hostname, connect_kwargs=parameters)
        connections.append(conn)
    
    with SerialGroup.from_connections(connections) as group:
        result = group.run('uname -a')
    
    for conn, conn_result in result.items():
        print(conn, conn_result)