前言
因为有约200台的网络设备需要每天登录巡检、查看配置、保存配置、定期更改密码(每周改一次),如果都手动去登录、配置将是非常耗费时间和人力的,所以就有了整理出脚本的想法。查看了网上大多是VBS编写的脚本,我对VBS不熟悉,刚好前段时间初步学习了Python,就想用Python整理一些自己需要的脚本。
提示:以下是本篇文章正文内容,下面案例可供参考
一、脚本主要功能
自动的逐台登录设备,并执行相关命令;
记录屏幕输出并保存到TXT文件中,将TXT文件以设备名、设备IP、时间命名。
二、脚本示例
# $language = "python"
# $interface = "1.0"
import time
import os
import csv
user = 'admin'
passwd = 'huawei@123'
# 定义一个变量,名为current_time,把当前PC的时间格式化后赋值给该变量
current_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
def main():
# 设置CRT的屏幕同步属性为False。具体作用自行百度。
crt.Screen.Synchronous = False
# 通过with open打开ip.txt文件,获取文件中的所有IP地址。txt文件中一个IP占用一行。
with open('ip.txt', 'r') as rfile:
host_list = rfile.readlines()
for host in host_list:
# 由于readlines()方法在获取txt中的IP时,会把换行符读取出来,赋值给host_list变量时IP地址后边跟了“
”导致CRT无法读取争取的IP,所以使用split()方法分割字符串,获取正确的IP地址信息。
cmd = '/SSH2 /L %s /PASSWORD %s /C 3DES /M MD5 %s' % (user, passwd1, host.split()[0])
crt.Session.ConnectInTab(cmd)
time.sleep(1)
crt.Screen.Send('
')
crt.Screen.Send('
')
crt.Screen.WaitForString('>')
# 把log_name()函数的值赋给current_name这个变量。
current_name = log_name()
time.sleep(1)
# 给txt文件命名。
crt.Session.LogFileName = current_name + "_" + host.split()[0] + "_" + current_time + "_log.txt"
crt.Session.Log(True)
time.sleep(1)
crt.Screen.Send('
')
crt.Screen.WaitForString('>')
crt.Screen.Send('display cur
')
# 因为会有很多遇到more的情况,而我们又无法确定要输入几次空格,所以通过while循环中的条件判断,实现不同情况的处理。
while True:
crt.Screen.WaitForStrings([" ---- More ----", '')
time.sleep(1)
crt.Screen.Send('
')
break
crt.Screen.Send('
')
crt.Screen.Send('
')
crt.Screen.WaitForString('>')
crt.Screen.Send('display ip inter brie
')
crt.Screen.Send('
')
crt.Screen.Send('
')
crt.Screen.WaitForString('>')
crt.Screen.Send('quit
')
time.sleep(3)
def log_name():
# 定义一个还书获取屏幕当前设备名称
rowIndex = crt.Screen.CurrentRow
colindex = crt.Screen.CurrentColumn - 1
chushi_name = crt.Screen.Get(rowIndex, 1, rowIndex, colindex)
name = chushi_name.strip('<>')
return name
main()
审核编辑:汤梓红
全部0条评论
快来发表一下你的评论吧 !