一、概述
随着设备基数增多,很多重复操作只用手工操作浪费时间精力,而python正是提高此类工作效率的好工具。
脚本演示
二、文件目录操作OS库
OS库中通常用到两个功能;
os.chdir(r"C:\py_config\按设备类型操作") //改变工作目录,如果我们存放信息的文件在某个目录中,通过此功能把工作目录调整到相关目录下运行才能正常。
os.listdir() //列出当前目录下的文件或者文件夹名字,返回一个列表
三、for循环
for循环可以遍历任何可迭代对象,如一个列表或者一个字符串;一般格式为
for <variable> in <sequence>:
<statements>
四、字符串操作
字符串是 Python 中最常用的数据类型。python中字符串的处理一般都是分割截取得到自己想要的字符串,比如文本中的ip信息192.168.1.1@ruijie,通过截取得到IP地址192.168.1.1和设备类型ruijie;具体使用为 字符串变量[起始值:结束值],起始值包含起始值,结束值不包含结束值。例如字符串 a="abcdefg",a[2:4]=cd
五、文件读写
open 方法用于打开一个文件,并返回文件对象。一般使用方法为:
with open("xxx.txt","r",encoding="utf-8",errors="ignore") as f:
content=f.read()
f.close()
打开之后调用close关闭;
参数含义:
xxx.txt要打开的文件
"r"操作模式:r只读,指针在文件开头;w只写,如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件;a+,打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
encoding="utf-8":使用utf-8编码
errors="ignore":忽略密文错误,有些文本有密文,不带此参数会出现错误。
f.read():读取文件所有内容
readlines()方法用于读取所有行并返回列表;
write()方法用于向文件中写入指定字符串。
六、异常处理
程序在运行中如果遇到某些异常会导致程序无法继续允许,使用异常处理可以跳过这些异常记录信息并继续执行程序,登陆网络设备一般的异常为用户名密码不正确,目标网络不可达等等。异常的语句如下:
异常处理流程
七、SSH登陆操作模块paramiko
paramiko库属于第三方库,使用时需要安装,是一个基于SSH用于连接远程登陆设备并执行相关操作,我们一般用到的有以下几个方法:
SSHClient():实例化SSH
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) :自动添加主机名及主机密钥到本地HostKeys对象,不依赖load_system_host_key的配置。即新建立ssh连接时不需要再输入yes或no进行确认。
ssh_client.connect(hostname=ip, username=username, password=password):ssh连接远程设备
command = ssh_client.invoke_shell():实例化ssh客户端的shell命令行
command.send(comm_str):发送命令
result = command.recv(-1):接收所有返回
ssh_client.close():关闭ssh客户端
八、进程模块threading
登陆设备比较多时必须使用多线程或者多进程提高程序效率,比如登陆10台设备,每台设备程序运行10秒钟,那么在没有多线程或者多进程的情况下需要100秒执行完,在使用多线程或者多进程的情况下只需要10秒就执行完所有设备;
threading方法如下:
run(): 用以表示线程活动的方法。
start():启动线程活动。
join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
isAlive(): 返回线程是否活动的。
getName(): 返回线程名。
setName(): 设置线程名。
调用方法为threading.Thread(target=function, args=(xx,xx))
九、re模块
正则表达式能精确匹配各种想要的数据,但是表达式比较抽象,此处介绍一种比较通用的匹配方法,举个栗子:
a=“abc123bd5123ghj95kkh”,匹配以3开头,5结尾的字符串时可以这样写
a_list=re.compile(a_pat,re.S).findall(a)
if a_list:
print(a_list)
结果为:['bd', 'ghj9']
十、操作脚本参考
脚本功能:登陆某一类型的设备执行命令取得返回结果。
import os, re, time, socket, paramiko, threading #导入各种模块,OS目录操作,re正则匹配
#获取用户名密码并返回
def get_user():
os.chdir(r"C:\py_config\按设备类型操作")
with open("用户名密码.txt","r",encoding="utf-8") as f:
user_password=f.read()
f.close()
user_password=user_password.replace("\n","")
return user_password
# 获取命令行,返回命令
def get_command():
os.chdir(r"C:\py_config\按设备类型操作")
command_list=[]
with open("设备命令行.txt", "r", encoding="utf-8") as f:
command = f.readlines()
f.close()
for comm in command:
if "\n" == comm:
pass
elif "\n" not in comm:
comm=comm+"\n"
command_list.append(comm)
else:
command_list.append(comm)
return command_list
#获取操作设备地址
def get_iptotal():
os.chdir(r"C:\py_config\按设备类型操作")
ip_total=[]
with open("同一类型设备地址.txt","r",encoding="utf-8") as f:
ip_total_list=f.readlines()
f.close()
for ip in ip_total_list:
if "\n" in ip:
ip=ip.replace("\n","")
ip_total.append(ip)
else:
ip_total.append(ip)
return ip_total
#保存收集日志,传入ip地址和设备配置文件
def save_log(ip_address, device_cfg):
os.chdir(r'C:\py_config\按设备类型操作\日志收集')
log_name = ip_address + '.log'
# data = result.decode('utf-8')
try:
with open(log_name, 'w', encoding='utf-8') as f:
f.write(device_cfg)
f.flush()
time.sleep(2)
f.close()
except Exception:
with open(log_name, 'wb') as f:
f.write(device_cfg)
f.flush()
time.sleep(2)
f.close()
#获取命令行登陆操作,传入地址和命令行
def device_login(ip,user_pass,command_list,time_delay):
username=user_pass[:user_pass.index("|")]
password=user_pass[user_pass.index("|")+1:]
ssh_client = paramiko.SSHClient() # 实例化SSH
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接设备
try:
print(f"正在登录 {ip} ", end="\n")
ssh_client.connect(hostname=ip, username=username, password=password)
print("收集信息", end="\n")
# 实例化ssh客户端命令行
command = ssh_client.invoke_shell()
# 向设备发出命令并收集返回的结果
for comm_str in command_list:
command.send(comm_str)
time.sleep(time_delay)
print(f"设备{ip}日志收集完成", end="\n")
result = command.recv(-1)
ssh_client.close()
save_log(ip, result)
except paramiko.ssh_exception.AuthenticationException as err:
# 提示用户名或者密码错误
print(f"设备{ip}用户名或者密码错误,请确认!!!")
os.chdir(r'C:\py_config\按设备类型操作\日志收集')
# 存入列表中
with open("密码不正确.txt", "a+") as f:
f.write(ip)
f.write('\n')
f.flush()
f.close()
except socket.error:
# 提示用户网络不可达
print(f"设备{ip}网络不可达,请确认!!!")
os.chdir(r'C:\py_config\按设备类型操作\日志收集')
# 存入列表中
with open("目标不可达.txt", "a+") as f:
f.write(ip)
f.write('\n')
f.flush()
f.close()
except paramiko.ssh_exception.SSHException as un:
os.chdir(r'C:\py_config\按设备类型操作\日志收集')
with open("other.txt", "a+") as f:
f.write(ip)
f.write('\n')
f.write(str(un))
f.write('\n')
f.flush()
f.close()
except Exception as oth:
os.chdir(r'C:\py_config\按设备类型操作\日志收集')
with open("other.txt", "a+") as f:
f.write(ip)
f.write('\n')
f.write(str(oth))
f.write('\n')
f.flush()
f.close()
if __name__=="__main__":
threads = []
#收集用户名密码
user_pass=get_user()
time_delay=int(input("请输入执行命令等待时延:\n"))
command_list=get_command()
ip_list=get_iptotal()
for ip in ip_list:
t = threading.Thread(target=device_login, args=(ip,user_pass,command_list,time_delay))
time.sleep(0.3)
t.start()
threads.append(t)
for t in threads:
t.join()
行动吧,在路上总比一直观望的要好,未来的你肯定会感谢现在拼搏的自己!如果想学习提升找不到资料,没人答疑解惑时,请及时加入群: 759968159,里面有各种测试开发资料和技术可以一起交流哦。
最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】
软件测试面试文档
我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。