python-多线程批量管理主机

多线程批量管理主机: 利用threading.Thread继承的方式实现.

import threading
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException

class IpThread(threading.Thread):
    def __init__(self,cmd,hostname,port=22,user='root'):
        super(IpThread, self).__init__()
        self.cmd=cmd
        self.hostname=hostname
        self.port=port
        self.user=user
    def run(self):
        client = paramiko.SSHClient()
        private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            client.connect(hostname=self.hostname,
                           port=self.port,
                           username=self.user,
                           pkey=private_key
                           )
            stdin, stdout, stderr = client.exec_command(self.cmd)
        except NoValidConnectionsError as e:
            print("%s连接失败" % (self.hostname))
        except AuthenticationException as e:
            print("%s密码错误" % (self.hostname))
        except TimeoutError as  e:
            print("%s连接超时" % (self.hostname))
        else:
            result = stdout.read().decode('utf-8')
            print('%s' % (self.hostname), result)
        finally:
            client.close()
def use_thread():
    threads = []
    ips = ['172.25.254.%s' %(i)  for i in range(1,254)]
    for ip in ips:
        t = IpThread(cmd='uname',hostname=ip)
        threads.append(t)
        t.start()
    [thread.join() for thread in threads]
if __name__ == '__main__':
    use_thread()

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_42687283/article/details/82718385
今日推荐