1. 程式人生 > 程式設計 >python利用paramiko實現交換機巡檢的示例

python利用paramiko實現交換機巡檢的示例

直接上程式碼

#-*- coding:UTF-8 -*-
import paramiko
import time
starttime = time.strftime('%Y-%m-%d %T')
start_info = "巡檢開始時間:"+str(starttime)
cmd_filepath = r"d:\Python\py\xunjian\cmd.txt"
cmd_file = open(cmd_filepath,"r")
cmds = cmd_file.readlines()
dev_filepath = r"d:\Python\py\xunjian\device_info.txt"
dev_file = open(dev_filepath,"r")
while 1: 
  dev_info = dev_file.readline()
  if not dev_info :
    break
  else :
    devs = dev_info.split(',') 
    ip = devs[0]
    username = devs[1]
    password = devs[2].strip()
    password = password.strip('\n')
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname = ip,username = username,password = password)
    print("成功連線",ip)
    command = ssh.invoke_shell()
    time.sleep(3)
    command.send('N\n') #該行非必須
    command.send('screen-length 0 temporary\n') #取消分屏顯示
    for cmd in cmds:
    command.send(cmd+'\n')
    time.sleep(5)
    output = command.recv(65535).decode()
    log = open(r"d:\Python\py\xunjian\\"+ip+".txt",'a')
    endtime = time.strftime('%Y-%m-%d %T')
    end_info = "巡檢結束時間:"+str(endtime)
    log.write(start_info+'\n\n'+output+'\n\n'+end_info)
    log.close()
dev_file.close()

#巡檢命令文件cmd.txt
display device
display environment
display alarm urgen
display memory-usage
display cpu-usage
display logbuffer level 0
display logbuffer level 1
display logbuffer level 2
display logbuffer level 3
display logbuffer level 4
#裝置資訊 device_info.txt
192.168.10.11,admin,Huawei@123
192.168.10.12,Huawei@123
192.168.10.13,Huawei@123
192.168.10.14,Huawei@123

以上就是python利用paramiko實現交換機巡檢的示例的詳細內容,更多關於paramiko交換機巡檢的資料請關注我們其它相關文章!