自动化运维基础基础1-使用python3通过telnet访问华为交换机并导出配置

访问交换机都需要使用远程模块,因此需要添加telnetlib或者paramiko,telentlib3是用于telnet的,paramiko是用于ssh的,以telnet登录方式为例

import telentlib #引入telnetlib
import time #引入倒计时
import datetime #引入时间

host = "x.x.x.x"
user = "xx"
password = "xxxx"

tn = telnetlib.Telnet(host)
tn.read_until(b'Username:') #python3的telnetlib所有函数返回值均为"字节串"(由unicode字符组成,长度0-255用于处理二进制数),而从交换机上读取的数据Username本身是字符串,需要修改成字节串才能被read_until()函数识别,将字符串修改成字节串只需要在字符串前面加B/b即可,反之加U/u
tn.write(user.encode('ascii') + b"\n")
tn.read_until(b'Password:')
tn.write(password.encode('ascii') + b"\n")
tn.read_until(b'>')
tn.write(b'system-view\n')
tn.write(b'user-interface vty 0 4\n')
tn.write(b'screen-length 0\n') #关闭分页显示,这样就不需要重复按回车
tn.write(b'display current-configuration\n')
time.sleep(5)
tn.write(b'quit\n')
output = tn.read_very_eager().decode('ascii') #华为设备无法支持使用tn.read_all()因此只能使用read_very_eager()
print(output)
tn.close()

timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S') #调用datetime模块的当前时间并转换时间戳的格式为“年-月-日_时-分-秒”
filename = f"{host}_{timestamp}.cfg" #将文件名称以主机IP+时间戳的格式命名

with open(filename,'a+') as f : #打开/创建一个名称为config的文件,把output写入
f.write(output)
f.close()

posted @ 2025-08-01 14:49  yl1010110  阅读(76)  评论(0)    收藏  举报