如何使用python通过telnet批量登录华为交换机,下图是演示环境
配置telnet服务器
这里我们在R1路由器上配置下telnet登录配置,从而能够通过本地telent登录;
[R1]telnet server enable [R1]user-interface vty 0 4 [R1-ui-vty0-4]authentication-mode aaa [R1]aaa [R1-aaa]local-user huawei password cipher huawei [R1-aaa]local-user huawei service-type telnet [R1-aaa]local-user huawei privilege level 3
在本地验证下,可以登录路由器R1
使用python脚本登录设备
要通过 Python 脚本使用 Telnet批量登录华为交换机,你可以使用第三方库如 telnetlib 来实现。
首先,确保你已经安装了 telnetlib 库,如果没有安装,可以使用以下命令安装:
pip install telnetlib
然后,可以使用下面的 Python 脚本来实现批量 Telnet 登录和执行命令:
import telnetlib def telnet_login(host, username, password, commands): try: # 连接 Telnet 服务器 tn = telnetlib.Telnet(host) # 输入用户名 tn.read_until(b"Username:") tn.write(username.encode('ascii') + b"\n") # 输入密码 tn.read_until(b"Password:") tn.write(password.encode('ascii') + b"\n") # 登录成功后执行命令 for cmd in commands: tn.write(cmd.encode('ascii') + b"\n") output = tn.read_until(b">").decode('ascii') # 根据设备的提示符来调整 print(output) # 打印命令输出 print("1") # 退出 Telnet tn.write(b"quit\n") tn.close() except Exception as e: print(f"Telnet connection to {host} failed: {e}") if __name__ == "__main__": host_list = ["192.168.56.2"] # 设备的 IP 地址列表 username = "huawei" password = "huawei" commands_to_run = ["display version", "display interface brief",""] # 要执行的命令列表 for host in host_list: print(f" Connecting to {host}...") telnet_login(host, username, password, commands_to_run)
在这个脚本中:
- telnet_login 函数用于连接到 Telnet 服务器,并执行指定的命令。
- host_list 是要连接的设备列表。
- username 和 password 是用于 Telnet 认证的凭据。
- commands_to_run 是要在每台设备上执行的命令列表。
- 脚本会遍历设备列表,对每个设备执行 Telnet 登录和指定的命令,并输出命令的结果。
python执行结果
Connecting to 192.168.56.2... Info: The max number of VTY users is 10, and the number of current VTY users on line is 1. The current login time is 2024-04-09 22:21:33. display version Huawei Versatile Routing Platform Software VRP (R) software, Version 5.110 (eNSP V100R001C00) Copyright (c) 2000-2011 HUAWEI TECH CO., LTD display interface brief PHY: Physical *down: administratively down ^down: standby (l): loopback (s): spoofing (b): BFD down (e): ETHOAM down (d): Dampening Suppressed InUti/OutUti: input utility/output utility Interface PHY Protocol InUti OutUti inErrors outErrors Ethernet0/0/0 up up 0% 0% 0 0 Ethernet0/0/1 up up 0% 0% 0 0 GigabitEthernet0/0/0 down down 0% 0% 0 0 GigabitEthernet0/0/1 down down 0% 0% 0 0 GigabitEthernet0/0/2 down down 0% 0% 0 0 GigabitEthernet0/0/3 down down 0% 0% 0 0 NULL0 up up(s) 0% 0% 0 0 Serial0/0/0 down down 0% 0% 0 0 Serial0/0/1 down down 0% 0% 0 0 Serial0/0/2 down down 0% 0% 0 0 Serial0/0/3 down down 0% 0% 0 0 ---END---
本文由 @老豆 发布于弱电智能网 。
题图来自Unsplash,基于CC0协议
内容观点仅代表作者本人,弱电智能网平台仅提供信息存储空间服务。
如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
文章名称:《华为交换机如何使用python脚本批量登录?》
文章链接:https://www.ruodian360.com/tech/networking/53599.html
添加微信ydian188免费入群,记得备注“弱电智能网”。