Python3 uses the paramiko module and threading module to implement batch management of the host and execute commands

import paramiko
import sys
from getpass import getpass
import threading

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

if __name__ == '__main__':
    host_file = sys.argv[1]
    command = sys.argv[2]
    pwd = getpass()
    with open(host_file) as fobj:
        for line in fobj:
            host = line.strip()
            t = threading.Thread(target=remote_command, args=(host, pwd, command))
            t.start()

Published 73 original articles · praised 4 · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_27592485/article/details/102558659
Recommended