How to use this script for a server list? - Python

Asked

Viewed 228 times

0

Good afternoon, you guys.

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

http://alissonmachado.com.br/python-e-ssh/

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 as follows: How do I run this command on not one, but on multiple servers at the same time? a list.

2 answers

2

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

But since it is an external resource, you can use the module asyncio to manage tasks through coroutines. This way, your code will tend to run faster than done sequentially.

If you have a server list, with user 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 seen here: http://asyncssh.readthedocs.io/en/latest/

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

  • I think I expressed myself badly. Actually, I meant: It rotates in one, then another, then another, then another.. No need for me to put the IP.

0

Use a repeat structure like the 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")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.