美文网首页
Python多线程配置服务器

Python多线程配置服务器

作者: Bless_H | 来源:发表于2022-03-08 00:25 被阅读0次

*仅测试了centos


import paramiko
import threading
import argparse

def do_job(host,username,password,exec_cmd,port):

    ssh = paramiko.SSHClient()
    key = paramiko.AutoAddPolicy()
    ssh.set_missing_host_key_policy(key)

    try:
        ssh.connect(hostname=host, port=port, username=username, password=password, timeout=10)
        stdin, stdout, stderr = ssh.exec_command(exec_cmd)
        print('{}: \n {}'.format(host,stdout.read().decode()))
        ssh.close
    except:
        print('{}: \n {}'.format(host,'user_name or password error'))

class MyThread(threading.Thread):
    def __init__(self, func, args):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result
        except Exception:
            print('Error item: {}'.format(str(self.args)))
            return None

def main():

    li=[]

    parser = argparse.ArgumentParser(description='python3 ./exec_command.py '+ '-f <ip.txt> -u <root> -p <password> -c <commad>')
    parser.add_argument('-f', dest='ip_file',
                        help='ip file location')
    parser.add_argument('-u', dest='username', 
                        help='username for the servers')
    parser.add_argument('-p', dest='password', 
                        help='password for the servers')
    parser.add_argument('-P', nargs = "?", type=int, dest='port', default=22,
                        help='ssh port')
    parser.add_argument('-c', dest='exec_cmd', 
                        help='command')
    arguments = parser.parse_args()

    #get the value of argument
    ip_file = arguments.ip_file
    username = arguments.username
    password = arguments.password
    exec_cmd = arguments.exec_cmd
    port = arguments.port

    if ip_file == None or username == None or password == None or exec_cmd == None:
        print(parser.print_help())
        exit(0)
    #if 'reboot' or 'restart' in exec_cmd:
    #    print()

    file = open(ip_file)
    ip_list = file.readlines()

    for host in ip_list:
        host= host.rstrip()
        t = MyThread(do_job, args=(host,username,password,exec_cmd,port))
        li.append(t)
        t.start()

    print('Begin to login server:')
    for t in li:
        t.join()  # 一定要join,不然主线程比子线程跑的快,会拿不到结果
        t.get_result()

if __name__ == "__main__":
    main()

相关文章

网友评论

      本文标题:Python多线程配置服务器

      本文链接:https://www.haomeiwen.com/subject/triorrtx.html