首页
python
Win桌面应用自动化pywinauto
pywinauto遍历展示程序的所有菜单项
Python3使用串口
Python字符串处理
Python3实现配置文件差异对比(键值对key=value的形式)
正则
正则匹配两个字符之间的字符串
正则提取markdown中图片链接
正则表达式基本知识
字符串-正则实例
Python生成8位随机字符串的一些方法
python3批量ping检测
python3检测一批主机ip的tcp端口
Python3--DNS
3D人体骨架检测(mediapipe)
Python-网络
检测到win电脑断网就发出告警声音
Python编写的DNS服务可靠性测试程序
Python编写的TCP/UDP端口探测程序
Python抓包-Pyshark
并发扫描TCP、UDP端口
Python-DHCP
端口的问题以及绑定端口(Python)
VSCode编辑器
python远程开机工具
Pyhton3--Win注册表
开源IT运维项目
python知识点
Python开源运维项目集合
python3备份交换机配置
Python3使用snmp获取H3C交换机arp表
Python检测tcp端口状态并发送到企微群
Python3使用smtp发邮件
Python3使用smtp发邮件(带附件)
Python3拉取微软AD域所有用户信息
Python3使用微软AD域账号认证
自动更新公网域名的解析(阿里云)
每日定时推送Excel中排班表信息到企微群
Django
Django模板标签
Django在发送POST请求时返回403错误
Django-mysql数据库条件查询
uwsgi 配置 python virtualenv 虚拟环境目录 ( ini 配置)
常用收藏
python3数据类型转换
python处理文本
txt每行一个字符串_用英文逗号连接
txt_匹配并拆分出需要字符串
python获取日期时间
python执行linux命令的三种方式
python使用ssh连接到linux服务器执行命令
本文档由 内网文摘 发布,转载请注明出处
-
+
首页
python3备份交换机配置
支持ssh和telnet方式,可以自定义ip,port,username,password,思科的en密码 ```python #coding=utf-8 import paramiko import datetime import time import re import telnetlib # import difflib # import smtplib # from email.MIMEMultipart import MIMEMultipart # from email.MIMEText import MIMEText # v0.1 每行一个交换机ip # v0.2 账号密码可配置 ip,username,password # v0.3 适配不同厂商 # v0.4 ssh telnet 未实现,阶段留存1 # v0.4.1 增加telnet # v0.5 备份兼容 华三 华为 思科 # (思科ssh自定义端口+en密码测试正常),未按预定义返回数据直接跳过,如密码错误等(待完善) # v0.6 增加设备标签用于给配置备份文件命名 # v0.6.1 修复兼容h3c ssh S5560s-52c-EI,修复兼容telnet h3c S7503E(用:h3c,其他型号:H3C) # v0.6.2 修复兼容H3C S5560X-30C-EI-1119P20 原因为登陆后提示信息和<hostname>分开返回导致判断时为搜索到<> ''' # v0.5 #预定义默认值 #default_model = "h3c" ##h3c huawei cisco #default_connect = "ssh" ##ssh telnet #default_sport = 22 #default_tport = 23 #default_timeout = 8 #5列依次填写,英文逗号分隔 #厂商 协议 地址(地址:端口) 用户名 密码(密码:en密码) #huawei,ssh,192.168.1.1:2222,admin,admin #h3c,telnet,192.168.1.1,admin,admin #4列依次填写,英文逗号分隔 #厂商 地址(地址:端口) 用户名 密码(密码:en密码) default_connect = "ssh" cisco,10.10.1.91:8092,admin,Localnetwork@.cn:admin [设备标签1] cisco,10.10.1.9:8092,admin,Localnetwork@.cn:admin cisco,10.10.1.8:8092,admin,Localnetwork@.cn:admin cisco,10.10.1.81:8092,admin,Localnetwork@.cn:admin [设备标签2] cisco,10.10.1.10:8092,admin,Localnetwork@.cn:admin cisco,10.10.1.11:8092,admin,Localnetwork@.cn:admin #3列依次填写,英文逗号分隔 #地址(地址:端口) 用户名 密码(密码:en密码) ''' class SwConfigBak: def MyRecv(self, command): print("接收数据") time.sleep(0.5) output = command.recv(65535) # print(output) print(output) try: output2 = output.decode('gbk') except UnicodeDecodeError: #print(output) try: output2 = output.decode('UTF-8') except UnicodeDecodeError: output2 = output.decode('ascii') print(output2) return output2 def SaveFile(self, mylabel, list_i_ip, output2): with open(mylabel + '_' + list_i_ip + '_' + datetime.date.today().isoformat() + '.txt', 'w+', encoding='UTF-8') as new_file: new_file.write(output2) # .decode('ascii') new_file.close() #new_file = open(list_i_ip + '_' + datetime.date.today().isoformat() + '.txt') def MyTelnetClient(self, mylabel, list_i_model, list_i_ip, Port, timeout, list_i_username, list_i_password): try: # 连接Telnet服务器 #Port = 23 tn = telnetlib.Telnet(list_i_ip, Port, timeout=timeout) #tn.set_debuglevel(3) if list_i_model == "h3c": # 输入登录用户名 tn.read_until(':'.encode('utf-8')) # username = username.strip('\n').encode('utf-8') tn.write(list_i_username.encode('utf-8') + b'\n') # 输入登录密码 tn.read_until('assword:'.encode('utf-8')) # password = password.strip('\n').encode('utf-8') tn.write(list_i_password.encode('utf-8') + b'\n') #判断密码是否正确 response = tn.read_until(">".encode('utf-8'), timeout=2) if ">".encode('utf-8') in response: print('收到>,密码正确,登陆成功') # 开始命令交互 tn.write(b'\n') tn.read_until('>'.encode('utf-8')) tn.write("screen-length disable".encode('utf-8') + b'\n') #tn.read_until(']'.encode('utf-8')) tn.write("display cu".encode('utf-8') + b'\n') print("接收数据") time.sleep(20) result = tn.read_very_eager().decode('utf-8', 'replace') #print(result) # print tn.read_all() self.SaveFile(mylabel, list_i_ip, result) else: pass print('未收到>,密码不正确') elif list_i_model == "H3C": # 输入登录用户名 tn.read_until('sername:'.encode('utf-8')) # username = username.strip('\n').encode('utf-8') tn.write(list_i_username.encode('utf-8') + b'\n') # 输入登录密码 tn.read_until('assword:'.encode('utf-8')) # password = password.strip('\n').encode('utf-8') tn.write(list_i_password.encode('utf-8') + b'\n') #判断密码是否正确 response = tn.read_until(">".encode('utf-8'), timeout=2) if ">".encode('utf-8') in response: print('收到>,密码正确,登陆成功') # 开始命令交互 tn.write(b'\n') tn.read_until('>'.encode('utf-8')) tn.write("screen-length disable".encode('utf-8') + b'\n') #tn.read_until(']'.encode('utf-8')) tn.write("display cu".encode('utf-8') + b'\n') result = tn.read_all() # print tn.read_all() self.SaveFile(mylabel, list_i_ip, result) else: # 第2次判断密码是否正确 response = tn.read_until(">".encode('utf-8'), timeout=2) if ">".encode('utf-8') in response: print('收到>,密码正确,登陆成功') # 开始命令交互 tn.write(b'\n') tn.read_until('>'.encode('utf-8')) tn.write("screen-length disable".encode('utf-8') + b'\n') # tn.read_until(']'.encode('utf-8')) tn.write("display cu".encode('utf-8') + b'\n') result = tn.read_all() # print tn.read_all() self.SaveFile(mylabel, list_i_ip, result) else: pass print('未收到>,密码不正确') elif list_i_model == "huawei": # 输入登录用户名 tn.read_until(':'.encode('utf-8')) # username = username.strip('\n').encode('utf-8') tn.write(list_i_username.encode('utf-8') + b'\n') # 输入登录密码 tn.read_until('assword:'.encode('utf-8')) # password = password.strip('\n').encode('utf-8') tn.write(list_i_password.encode('utf-8') + b'\n') # 判断密码是否正确 response = tn.read_until(">".encode('utf-8'), timeout=2) if ">".encode('utf-8') in response: print('收到>,密码正确,登陆成功') # 开始命令交互 tn.write(b'\n') tn.read_until('>'.encode('utf-8')) tn.write("screen-length 0".encode('utf-8') + b'\n') # tn.read_until(']'.encode('utf-8')) tn.write("display cu".encode('utf-8') + b'\n') result = tn.read_all(timeout=2) # print tn.read_all() self.SaveFile(mylabel, list_i_ip, result) else: pass print('未收到>,密码不正确') elif list_i_model == "cisco": # 输入登录用户名 tn.read_until('sername:'.encode('utf-8')) # username = username.strip('\n').encode('utf-8') tn.write(list_i_username.encode('utf-8') + b'\n') # 输入登录密码 tn.read_until('assword:'.encode('utf-8')) # password = password.strip('\n').encode('utf-8') tn.write(list_i_password.encode('utf-8') + b'\n') # 判断密码是否正确 response = tn.read_until(">".encode('utf-8'), timeout=2) if ">".encode('utf-8') in response: print('收到>,密码正确,登陆成功') # 开始命令交互 tn.write(b'\n') response = tn.read_until(">".encode('utf-8'), timeout=2) if ">".encode('utf-8') in response: #tn.read_until('>'.encode('utf-8')) tn.write("en".encode('utf-8') + b'\n') response = tn.read_until("passw".encode('utf-8'), timeout=2) if "passw".encode('utf-8') in response: tn.write(list_i_password.encode('utf-8') + b'\n') response = tn.read_until("#".encode('utf-8'), timeout=2) if "#".encode('utf-8') in response: tn.write("terminal length 0".encode('utf-8') + b'\n') tn.write("show run".encode('utf-8') + b'\n') result = tn.read_all() # print tn.read_all() self.SaveFile(mylabel, list_i_ip, result) else: print('未收到>,密码不正确') else: print("未知的设备厂商") except Exception as e: print("telnet错误:") print(e) pass def MySshClient(self, mylabel, list_i_model, list_i_ip, sport, timeout, list_i_username, list_i_password): print("执行ssh客户端", list_i_model, list_i_ip, sport, timeout, list_i_username, list_i_password) #return ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=list_i_ip, port=sport, username=list_i_username, password=list_i_password, timeout=timeout, look_for_keys=False) command = ssh_client.invoke_shell() if list_i_model == "h3c": print("已成功登陆交换机: ", list_i_ip) output2 = self.MyRecv(command) t1 = self.terminal_stdout_re[0].findall(output2) # 接收到 < > if t1: command.send('screen-length disable\n') command.send('display current-configuration\n') time.sleep(5) output2 = self.MyRecv(command) # output2 = output2.encode('UTF-8').decode('UTF-8') print("*********接收数据,保存中********\n") self.SaveFile(mylabel, list_i_ip, output2) print("*********接收数据保存成功********\n") else: time.sleep(2) output3 = self.MyRecv(command) t2 = self.terminal_stdout_re[0].findall(output3) # 接收到 < > if t2: command.send('screen-length disable\n') command.send('display current-configuration\n') time.sleep(5) output2 = self.MyRecv(command) # output2 = output2.encode('UTF-8').decode('UTF-8') print("*********接收数据,保存中********\n") self.SaveFile(mylabel, list_i_ip, output2) print("*********接收数据保存成功********\n") else: print("第二次没有接收到预定符号<>") pass # 没有接收到预定符号 #time.sleep(2) command.send('\n\n') output3 = self.MyRecv(command) t2 = self.terminal_stdout_re[0].findall(output3) # 接收到 < > if t2: command.send('screen-length disable\n') command.send('display current-configuration\n') time.sleep(5) output2 = self.MyRecv(command) # output2 = output2.encode('UTF-8').decode('UTF-8') print("*********接收数据,保存中********\n") self.SaveFile(mylabel, list_i_ip, output2) print("*********接收数据保存成功********\n") else: print("第3次没有接收到预定符号<>,结束") elif list_i_model == "huawei": print("已成功登陆HUAWEI交换机: ", list_i_ip) output2 = self.MyRecv(command) t1 = self.terminal_stdout_re[0].findall(output2) # 接收到 < > if t1: command.send('screen-length 0\n') command.send('display cu\n') time.sleep(5) output2 = self.MyRecv(command) # output2 = output2.encode('UTF-8').decode('UTF-8') print("*********接收数据,保存中********\n") # print(output.decode('ascii')) self.SaveFile(mylabel, list_i_ip, output2) print("*********接收数据保存成功********\n") pass else: output3 = self.MyRecv(command) t2 = self.terminal_stdout_re[0].findall(output3) # 接收到 < > if t2: command.send('screen-length 0\n') command.send('display cu\n') time.sleep(5) output2 = self.MyRecv(command) # output2 = output2.encode('UTF-8').decode('UTF-8') print("*********接收数据,保存中********\n") # print(output.decode('ascii')) self.SaveFile(mylabel, list_i_ip, output2) print("*********接收数据保存成功********\n") pass else: print("没有接收到预定符号<>") pass # 没有接收到预定符号 elif list_i_model == "cisco": print("已成功登陆CISCO交换机: ", list_i_ip) output2 = self.MyRecv(command) t1 = self.terminal_stdout_re[2].findall(output2) # 接收到 <> [] > # if t1: #print(t1) # ['\nSW-9FJ-A>'] command.send('en\n') output2 = self.MyRecv(command) t1 = self.terminal_stdout_re[4].findall(output2) # 接收到 <> [] > # Password if t1: print('en密码:%s\n' % self.list_i_en_password) command.send('%s\n' % self.list_i_en_password) #测试 # command.send('%s\n' % list_i_password) else: print(t1) output2 = self.MyRecv(command) t1 = self.terminal_stdout_re[3].findall(output2) # 接收到 <> [] > # passw if t1: command.send('terminal length 0\n') command.send('show run\n') time.sleep(5) # output = command.recv(65535).decode("ascii") # output = command.recv(65535).decode('gb2312') # output = command.recv(65535).decode('utf-8') # output = command.recv(65535).decode('gbk') output2 = self.MyRecv(command) print("*********接收数据,保存中********\n") # print(output.decode('ascii')) self.SaveFile(mylabel, list_i_ip, output2) print("*********接收数据保存成功********\n") pass else: pass terminal_stdout_re = [ re.compile(r'[\r\n]?<.+>(?:\s*)$'), re.compile(r'[\r\n]?\[.+\](?:\s*)$'), re.compile(r'[\r\n]?.+>(?:\s*)$'), re.compile(r'[\r\n]?.+#(?:\s*)$'), re.compile(r'password', re.IGNORECASE)] def mystart(self): f = open('swip_list6.txt', "r", encoding='UTF-8') # 预定义默认值 default_model = "h3c" default_connect = "ssh" default_sport = 22 default_tport = 23 default_timeout = 8 mylabel = "" for line in f.readlines(): print(line) try: line = line.strip('\n').strip() # 去掉列表中每一个元素的换行符,再用strip去掉空格 t1 = self.terminal_stdout_re[1].findall(line) # 接收到 <> [] > # if t1: print("检查配置文件中[]里的标签,结果:%s" % t1) mylabel = '_'.join(t1) # print(mylabel) kv = line.split("=") if line.startswith("#"): #print("#开头,为注释行") pass elif len(kv) == 2: if kv[0] == "device": default_model = kv[1] elif kv[0] == "connect": default_connect = kv[1] elif kv[0] == "sport": default_sport = kv[1] elif kv[0] == "tport": default_tport = kv[1] elif kv[0] == "timeout": default_timeout = int(kv[1]) else: pass else: pass user_list = line.split(",") if line.startswith("#"): #print("#开头,为注释行") pass elif len(user_list) == 5: # H3C,ssh,192.168.98.111,admin,admin list_i_model = user_list[0].strip() list_i_connect = user_list[1].strip() list_i_ip = user_list[2].strip() if len(list_i_ip.split(":")) == 2: list_i_port = int(list_i_ip.split(":")[1]) list_i_ip = list_i_ip.split(":")[0] else: list_i_port = False list_i_username = user_list[3].strip() list_i_password = user_list[4].strip() if len(list_i_password.split(":")) == 2: self.list_i_en_password = list_i_password.split(":")[1] list_i_password = list_i_password.split(":")[0] else: self.list_i_en_password = list_i_password if list_i_connect == "ssh": if list_i_port: pass else: list_i_port = default_sport print("即将登陆设备:{},{},{},{}".format(list_i_ip, list_i_port, list_i_username, list_i_password)) print(list_i_model, list_i_ip, list_i_port, default_timeout, list_i_username, list_i_password) self.MySshClient(mylabel, list_i_model, list_i_ip, list_i_port, default_timeout, list_i_username, list_i_password) elif list_i_connect == "telnet": if list_i_port: pass else: list_i_port = default_tport self.MyTelnetClient(mylabel, list_i_model, list_i_ip, list_i_port, default_timeout, list_i_username, list_i_password) else: pass # 其它未定义协议 elif len(user_list) == 4: #H3C,192.168.98.111,admin,admin 默认ssh # print("4") list_i_model = user_list[0].strip() list_i_ip = user_list[1].strip() if len(list_i_ip.split(":")) == 2: list_i_port = int(list_i_ip.split(":")[1]) list_i_ip = list_i_ip.split(":")[0] else: list_i_port = False list_i_username = user_list[2].strip() list_i_password = user_list[3].strip() if len(list_i_password.split(":")) == 2: self.list_i_en_password = list_i_password.split(":")[1] list_i_password = list_i_password.split(":")[0] else: self.list_i_en_password = list_i_password #if user_list[1].strip() == "ssh": #print("即将登陆设备:{},{},{}".format(list_i_ip, list_i_username, list_i_password)) if default_connect == "ssh": if list_i_port: pass else: list_i_port = default_sport print("即将登陆设备:{},{},{}".format(list_i_ip, list_i_port, list_i_username, list_i_password)) self.MySshClient(mylabel, list_i_model, list_i_ip, list_i_port, default_timeout, list_i_username, list_i_password) elif default_connect == "telnet": if list_i_port: pass else: list_i_port = default_tport self.MyTelnetClient(mylabel, list_i_model, list_i_ip, list_i_port, default_timeout, list_i_username, list_i_password) else: pass # 其它未定义协议 elif len(user_list) == 3: list_i_model = default_model list_i_ip = user_list[0].strip() if len(list_i_ip.split(":")) == 2: list_i_port = int(list_i_ip.split(":")[1]) list_i_ip = list_i_ip.split(":")[0] else: list_i_port = False list_i_username = user_list[1].strip() list_i_password = user_list[2].strip() if len(list_i_password.split(":")) == 2: self.list_i_en_password = list_i_password.split(":")[1] list_i_password = list_i_password.split(":")[0] else: self.list_i_en_password = list_i_password # if user_list[1].strip() == "ssh": # print("即将登陆设备:{},{},{}".format(list_i_ip, list_i_username, list_i_password)) if default_connect == "ssh": if list_i_port: pass else: list_i_port = default_sport print("即将登陆设备:{},{},{}".format(list_i_ip, list_i_port, list_i_username, list_i_password)) self.MySshClient(mylabel, list_i_model, list_i_ip, list_i_port, default_timeout, list_i_username, list_i_password) elif default_connect == "telnet": if list_i_port: pass else: list_i_port = default_tport self.MyTelnetClient(mylabel, list_i_model, list_i_ip, list_i_port, default_timeout, list_i_username, list_i_password) else: pass # 其它未定义协议 else: pass except Exception as e: print("错误") print(e) print("结束") if __name__ == '__main__': st = SwConfigBak() #SwConfigBak.mystart(st) st.mystart() ```
local
2022年4月27日 09:37
分享文档
收藏文档
上一篇
下一篇
微信扫一扫
复制链接
手机扫一扫进行分享
复制链接
关于 LocalNetwork
LocalNetwork
是由mrdoc开源
LocalNetwork.cn
修改的在线文档系统,作为个人和小型团队的云笔记、文档和知识库管理工具。
如果此文档给你或你的团队带来了帮助,欢迎支持作者持续投入精力更新和维护!内网文摘 & LocalNetwork
>>>主页
logo
logo
下载Markdown文件
分享
链接
类型
密码
更新密码