python-并行批量管理远程服务器(110)

#运行方式:python3 脚本名称 服务器的IP地址文件 "要在远程服务器上运行的命令"
import sys
import getpass
import paramiko     #基于SSH用于连接远程服务器并执行相关操作
import threading
import os

def remote_comm(host,pwd,command):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host,username='root',password=pwd) #连接要用的信息
    stdin,stdout,stderr = ssh.exec_command(command) #命令所对应的输入,输出,错误
    out = stdout.read() #定义输出
    err = stderr.read() #定义错误
    if out:
        print('[%s] OUT:\n%s' % (host,out.decode('utf8')))  #解码为utf8然后输出
    if err:
        print('[%s] ERROR:\n%s' % (host, err.decode('utf8')))
    ssh.close()

if __name__ == '__main__':
    if len(sys.argv) != 3:  #执行脚本时输入的不是三项
        print(print('Usage: %s ipaddr_file "command"' % sys.argv[0]))
        exit(1)
    if not os.path.isfile(sys.argv[1]): #脚本后面的第一个参数不是文件
        print('No such file:',sys.argv[1])
        exit(2)
    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))
        t.start()



# [root@room9pc01 python百例]# python3 110并行批量管理远程服务器.py  1.txt "id zhangsan"
# Password:
# [192.168.4.8] OUT:
# uid=1001(zhangsan) gid=1001(zhangsan) 组=1001(zhangsan)
#
# [192.168.4.6] OUT:
# uid=1001(zhangsan) gid=1001(zhangsan) 组=1001(zhangsan)
#
# [192.168.4.5] OUT:
# uid=1001(zhangsan) gid=1001(zhangsan) 组=1001(zhangsan)
#
# [192.168.4.7] OUT:
# uid=1001(zhangsan) gid=1001(zhangsan) 组=1001(zhangsan)

你可能感兴趣的:(python)