网络Python案例:华为路由器的路由表查看某ip路由并输出txt文件
网络Python案例:华为路由器的路由表查看某ip路由并输出txt文件



输出的txt文件:
f9371-A1-huawei_ssh_log_2025_05_24_18_04_44.txt


特点:
1、从txt读取多条命令,查看路由器的多个ip路由表并输出到txt文件中。
代码开始,如下:
#PyCharm 2023.3.3
#Python3.9.12
#Anaconda Navigator (Anaconda3)
# 使用说明:
#
# 使用说明:
#
# username1.txt格式:第一行IP地址,第二行用户名,第三行密码
# command-A1.txt每行一条华为路由器命令
# 需安装paramiko库:pip install paramiko
# 输出文件示例:router_output_2025_05_24_14_30_45.txt
#
# 该脚本针对华为设备优化了SSH连接参数,支持常见配置命令如display current-configuration等35,并处理了中文输出编码问题
import paramiko
import time
from datetime import datetime
import paramiko
import time
from datetime import datetime
def print_progress(current, total, message=""):
"""显示进度条和状态信息"""
progress = int(50 * current / total)
print(f"\r[{'#' * progress}{'.' * (50 - progress)}] {current}/{total} {message}", end='')
def get_credentials(filename):
"""从文件获取IP、用户名和密码"""
try:
with open(filename) as f:
lines = [line.strip() for line in f if line.strip()]
if len(lines) < 3:
raise ValueError("文件格式错误:需要包含IP、用户名和密码")
return lines[0], lines[1], lines[2]
except Exception as e:
print(f"\n❌ 读取认证文件失败: {str(e)}")
exit(1)
def get_commands(filename):
"""从文件读取命令列表"""
try:
with open(filename) as f:
commands = [line.strip() for line in f if line.strip()]
if not commands:
raise ValueError("命令文件为空")
return commands
except Exception as e:
print(f"\n❌ 读取命令文件失败: {str(e)}")
exit(1)
def execute_commands(ip, username, password, commands):
"""执行SSH命令并返回详细日志"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
log = f"=== SSH会话开始 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===\n"
log += f"目标设备: {ip}\n用户: {username}\n"
try:
print(f"\n? 正在连接 {ip}...")
client.connect(ip, username=username, password=password,
look_for_keys=False, timeout=10)
shell = client.invoke_shell()
time.sleep(1) # 等待会话建立
log += "连接状态: 成功\n"
print("✅ 连接成功,开始执行命令...")
total_commands = len(commands)
for idx, cmd in enumerate(commands, 1):
print_progress(idx, total_commands, f"正在执行: {cmd[:20]}...")
shell.send(cmd + '\n')
time.sleep(2) # 等待命令执行
output = ""
while shell.recv_ready():
output += shell.recv(9999).decode('utf-8', 'ignore')
log += f"\n[命令 {idx}/{total_commands}] {cmd}\n"
log += f"[输出]\n{output.strip()}\n"
log += "-" * 50 + "\n"
log += f"\n=== 所有命令执行完成 {datetime.now().strftime('%H:%M:%S')} ==="
return log
except Exception as e:
log += f"\n❌ 执行失败: {str(e)}\n"
return log
finally:
client.close()
print("\n")
def main():
print("=" * 50)
print("华为路由器SSH批量命令执行工具")
print("=" * 50)
ip, username, password = get_credentials('username1.txt')
commands = get_commands('command-A1.txt')
print(f"\n? 共加载 {len(commands)} 条命令")
print("⏳ 开始执行...")
output = execute_commands(ip, username, password, commands)
timestamp = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
output_filename = f"A1-huawei_ssh_log_{timestamp}.txt"
with open(output_filename, 'w', encoding='utf-8') as f:
f.write(output)
print(f"✅ 执行完成!详细日志已保存到 {output_filename}")
print("=" * 50)
if __name__ == "__main__":
main()代码结束,如上。
1、本站资源长期持续更新。
2、本资源基本为原创,部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
3、本站大部分文章的截图来源实验测试环境,请不要在生产环境中随意模仿,以免带来灾难性后果。
转载请保留出处: www.zh-cjh.com珠海陈坚浩博客 » 网络Python案例:华为路由器的路由表查看某ip路由并输出txt文件
2、本资源基本为原创,部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
3、本站大部分文章的截图来源实验测试环境,请不要在生产环境中随意模仿,以免带来灾难性后果。
转载请保留出处: www.zh-cjh.com珠海陈坚浩博客 » 网络Python案例:华为路由器的路由表查看某ip路由并输出txt文件
作者: 小编
| 手机扫一扫,手机上查看此文章: |
一切源于价值!
其他 模板文件不存在: ./template/plugins/comment/pc/index.htm