How to use this script for a list of servers? - Python

0

Good afternoon, guys.

I am using this code to update some servers here in my company, via ssh:

link

on line 11, we have:

self.ssh.connect(hostname='ip_do_servidor',username='Administrator',password='senha_servidor')

and on line 22, we have:

ssh.exec_cmd("update image force http://link_FTP")

The question is: How do I run this command on not one, but on multiple servers at the same time? a list.

    
asked by anonymous 06.08.2018 / 21:48

2 answers

0

Use a repeat structure such as for :

meus_servidores = [
    ('ip_do_servidor1', 'Administrator', 'senha_servidor1'),
    ('ip_do_servidor2', 'Administrator', 'senha_servidor2'),
    ('ip_do_servidor3', 'Administrator', 'senha_servidor3'),
    ('ip_do_servidor4', 'Administrator', 'senha_servidor4'),
]

for servidor, usuario, senha in meus_servidores:
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=servidor, username=usuario, password=senha)
    ssh.exec_command("update image force http://link_FTP")
    
06.08.2018 / 22:17
0

impossible It is very difficult to ensure that the command runs on all servers at the same time.

But since this is an external resource, you can use the asyncio module to manage tasks through corotines. In this way, your code will tend to run faster than you do sequentially.

If you have a list of servers, with username and password, you can do something like this:

import asyncio, asyncssh

async def update_image_force(host, user, pass):
    async with asyncssh.connect(host, username=user, password=pass) as ssh:
        await ssh.run('update image force http://link_FTP')

commands = asyncio.gather(*[update_image_force(server_data) for server_data in server_list])

loop = asyncio.get_event_loop()
loop.run_until_complete(commands)

The AsyncSSH documentation can be viewed here: link

The asyncio module is native to Python for versions greater than 3.6.

    
06.08.2018 / 22:40