110-Parallel batch management of remote servers

110-Parallel batch management of remote servers

The script is named remote_comm.py, and the execution method is as follows:

python3 remote_comm.py server IP address file "command to be executed on the remote server"

Such as:

# python3 remote_comm.py serverips.txt "useradd zhangsan"

The password of the remote server is obtained interactively

import sys
import getpass
import paramiko
import threading
import os

def remote_comm(host, pwd, command):
    ssh = paramiko.SSHClient()
    ssh.connect(hostname=host, username='root', password=pwd)
    stdin, stdout, stderr = ssh.exec_command(command)
    out = stdout.read()
    error = stderr.read()
    if out:
        print('[%s] OUT:\n%s'% (host, out.decode('utf8')))
    if error:
        print('[%s] ERROR:\n%s'% (host, error.decode('utf8')))

if __name__ =='__main__':
    if len(sys.argv) != 3:
        print('Usage: %s ipaddr_file "command"'% sys.argv[0])
    if not os.path.isfile(sys.argv[1]):
        print('No such file:', sys.argv[1])
    fname = sys.argv[1]
    command = sys.argv[2]
    pwd = getpass.getpass()
    with open(fname) as fobj:
        ips = [line.strip() for line in fobj]

    for ip in ips:
        t = threading.Thread(target=remote_comm, args=(ip, pwd, command))
Reference: https://cloud.tencent.com/developer/article/1334527 110-Parallel batch management of remote servers-Cloud + Community-Tencent Cloud