通过python3中的paramiko模块进行网络设备巡检

目标实现 1.读取需要巡检的-ip_lists.txt 2.读取-巡检命令列表.txt 3.创建-ip_times.txt 4.将巡检内容写入ip_times.txt 5*.用正则表达式处理文本(以后再补充)

import getpass import paramiko import time import datetimetimes = str(datetime.datetime.today().strftime('%Y_%m_%d_%H_%m'))# 处理时间并转成str()格式def login(hostname,username,password,port=22): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname,port,username,password) return sshdef commands_file(file):# 定义打开巡检命令文件的函数,巡检命令路径为:file with open(file) as file_commands: commands = file_commands.readlines() return commandsdef xunjian_ip(ip_lists):# 定义巡检ip地址列表 with open(ip_lists) as ip_list: hostnames = ip_list.readlines() return hostnameshostnames = xunjian_ip('/xx/ip_lists.txt') # 读取将要巡检的ip列表 username = 'admin' password = getpass.getpass() for hostname in hostnames: ssh = login(hostname.rstrip(),username,password) commands = commands_file('/xx/巡检命令列表.txt') for command in commands: stdin,stdout,stderr = ssh.exec_command(command.rstrip()) time.sleep(2) for line in stdout.readlines(): print(line.rstrip()) file2 = '/xx/' + str(hostname.rstrip()) +'_' + times +'.txt'# 创建ip_times.txt with open(file2,'a+') as files: files.write(line.rstrip() + "\n")

第一次写博客,学python也没多久,学python的目的就是自动巡检网络设备并用正则表达式处理文本。勤奋(懒)是人类进步的动力啊! 欢迎更正,优化,谢谢!

    推荐阅读