python脚本实现批量远程部署主机

python脚本实现批量远程部署主机

本脚本通过填写位置参数来实现批量部署远程主机的功能,位置参数1填写主机ip列表,位置参数2填写执行命令(执行命令写在" "内)

#!/root/bin/python
import paramiko
import sys
import getpass
import threading

def rcmd(host,user = 'student',passwd = None,port=22,commands = None):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host,username=user,password=passwd,port=port)
    stdin,stdout,stderr = ssh.exec_command(commands)
    out = stdout.read()
    err = stderr.read()
    if out:
        print('[\033[032;1m%s\033[0m] OUT:\n%s'% (host,out.decode()))
    if err:
        print('[\033[31;1m%s\033[0m] ERROR:\n%s'% (host,err.decode()))

if __name__ == '__main__':
    if len(sys.argv) !=3:
        print('Usage:%s ipfile "commands"'% sys.argv[0])
        exit(1)

    if not os.path.isfile(sys.argv[1]):
        print('no such file :%s'% sys.argv[1])
        exit(2)

    ipfile = sys.argv[1]
    commands = sys.argv[2]
    passwd = getpass.getpass()
    with open(ipfile) as  fobj:
        for line in fobj:
            ip = line.strip()
            # rcmd(ip,passwd=passwd,commands=commands)
            t = threading.Thread(target=rcmd,args=(ip,),kwargs={'passwd':passwd,'commands':commands})
            t.start()

你可能感兴趣的:(python,linux)