Python3 利用paramiko模塊,threading模塊,實現批量管理主機,執行命令

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()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章