Python-服务器&交换机自动化巡检
功能
远程登录多台linux服务器或交换机执行相应命令输出到txt文本。其中服务器ip列表(ip_file.txt)自定义,巡检命令列表(cmd_file.txt)自定义。 注意:交换机必须设置look_for_keys(bool类型),设置为False时用来禁用在~/.ssh中搜索私钥文件
环境准备
- linux系统
- python3环境
- python3模块paramiko
脚本内容
#vim check.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import re
import paramiko
import time
import datetime
def sshexeccmd(ip):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip.strip(), port=22, username='用户名', password='密码', look_for_keys=False)
print("You have successfully connect to ", ip)
command = ssh.invoke_shell()
cmdlist = open(r"./cmd_file.txt", 'r')
cmdlist.seek(0)
for line in cmdlist.readlines():
if len(line.strip()) == 0:
continue
command.send(line.strip())
command.send("\n")
time.sleep(3)
cmdlist.close()
output = command.recv(65535)
t = datetime.datetime.now()
# 对现在时间格式化,以此作为文件名
cur_time = t.strftime('%Y-%m-%d_%H-%M-%S')
save_file = open(ip.strip() + '_' + cur_time + '.txt', "wb")
save_file.seek(0)
save_file.write(output)
save_file.close()
ssh.close()
change_file = open(ip.strip() + '_' + cur_time + '.txt', "r")
alllines = change_file.readlines()
change_file.close()
change_file = open(ip.strip() + '_' + cur_time + '.txt', "w+")
for eachline in alllines:
a = re.sub(r"\[\?2004h", '', eachline)
a = re.sub(r"\[\?2004l", '', a)
change_file.writelines(a)
change_file.close()
except Exception as e:
print(e)
def main():
iplist = open(r"./ip_file.txt", 'r')
for line in iplist.readlines():
if len(line.strip()) == 0 :
continue
sshexeccmd(line)
main()
备注:username=’用户名’, password=’密码’ 记得修改
ip列表
#vim ip_file.txt
192.168.1.1 192.168.1.2
巡检命令列表
#vim cmd_file.txt
ifconfig hostname
执行脚本
条件:ip列表文件和巡检命令列表文件与python脚本文件要在同级目录下
#python3 check.py
结果
脚本执行完成之后会生成对应的结果文件
192.168.1.1_2022-09-16_09-09-56.txt
192.168.1.2_2022-09-16_09-09-57.txt


