python脚本批量更改ESXI主机名,DNS

made by G.M

#!/bin/env python
import paramiko,time,sys
###IP list###
f=open("ip.list",'r')
#######user  and  passport#####
username="root"
passw="xxxxx"
#############################
#############input  CMD######
cmd=['esxcli system hostname set --domain lfesxi.com','esxcli network  ip  dns  server add  -s 1
92.168.7.40']
#############################
list=[]
for i in f:
    list.append(i)
    f.close()
def ssh2(ip,username,passwd,cmd):
s=paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    s.connect(ip,22,username,passwd,timeout=5)
    stdin,stdout,stderr=s.exec_command(cmd)
    for i in stdout.readlines():
        print i,
        s.close()
except:
    print "username:%s\npasspw:%s\nIP:%s"%(username,passwd,ip),
    print "passwd or username error"
return
def main():
    if len(sys.argv) < 2 or sys.argv[1]!="start":
        print "%s need start"% sys.argv[0]
        sys.exit(-1)
    else:
        for i in list:
        print i
        l=i.split('.')
        hostname="esxcli system hostname set --host             esx"+l[2]+"-"+l[3]
        cmd.append(hostname)
        for c in cmd:
            print c
            ssh2(i,username,passw,c)
            time.sleep(1)
            cmd.pop()
if __name__ == "__main__":
    main()