[python]通過paramiko模塊批量執行命令的簡單腳本

最近在寫pyton的批量執行腳本,考慮到通過ssh方式執行就想到了paramiko模塊,現基本寫完,望高手補充、相互學習交流。


執行需要兩個文件,一個是host.cfg文件(存放主機IP地址、用戶名、密碼),一個是command.txt文件(存放指令)

#!/user/bin/env python
import sys
import paramiko
import time

def Testsshcon(ip,port,username,password):
    try:
        sshcon=paramiko.SSHClient()
        sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        sshcon.connect(ip,port,username,password,compress=True)
        #print "ok"
        #print 'ipaddress %s,port %d,uername %s,password %s'%(ip,port,username,password)
        stdin,stdout,sterr=sshcon.exec_command(command)
        print stdout.read()
        print sterr.read()
        sshcon.close()
    except Exception,e:
        print "connet error",e

if __name__=="__main__":
    trial = 0
    while True:
        with open('host.cfg', 'r') as f:
            host_num = 0
            for i in f:
                #data = []

                HOST,username,password = i.strip().replace('\n', '').split(",")
                with open('command.txt', 'r') as f:
                    for command in f:
                        Testsshcon(ip=HOST,port=22,username=username,password=password)
                #Testsshcon(ip=HOST,port=22,username=username,password=password)
                if not len(HOST):
                    continue
                #Testsshcon(ip=HOST,port=22,username=user,password=password)
                #data.append(HOST)
                #print data
                host_num += 1
                print 'Scaned %s is over,This is %d:'%(HOST,host_num)
                trial += 1
            print 'Finshed is %d:'%(trial)

        time.sleep(11)
        break

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