Python通过Telnet自动抓取路由器信息
背景:
公司里面有路由器,核心交换机和接入层交换机约五六十台,按照安全审计的要求,是要定期备份网络设备的配置信息,以确保故障损坏后,配置能迁移到备用交换机,保障网络安全。但是,问题来了,五六十台的配置文件要从设备里面导出来,这个工作量可不小,而且,人为操作的话,也会存在错误的风险。
解决方法:
笔者曾经使用过C# + netcat, 是可以实现这样的功能,但是netcat的安全性值得商榷。现在,有了python, 哈哈,都已经是a piece of cake. 具体的实现思路如下:
- 引用telnetlib类
Import telnetlib
- 设计函数:
Username=’’ //定义登录用户名
Passworld=’’ //定义密码
Def get_data():
tn=telnetlib.Telnet() //调用类并实例化
try:
tn.open('135.252.*.*',port=23) //尝试telnet连接
except:
logging.warning('Failed') //失败报错
tn.read_until(b'Username:',timeout=10) //成功telnet后等待出现用户名
tn.write(username.encode('ascii') + b'\n') //自动输入用户名
tn.read_until(b'Password:',timeout=10) //等待输入密码界面
tn.write(password.encode('ascii') + b'\n') //输入密码
time.sleep(2)
command_result=tn.read_very_eager().decode('ascii')
print(command_result) //输出当前屏幕显示
tn.write('terminal length 0'.encode('ascii')+b'\n') //发送‘termial length 0’, 用于返回结果一次性显示,不用分页
time.sleep(2)
tn.write('show ip dhcp binding'.encode('ascii')+b'\n') //执行命令,这里可以使用show running config
time.sleep(2)
tn.write('exit'.encode('ascii')+b'\n') //结束退出telnet
time.sleep(2)
info=str(tn.read_all(),encoding='utf-8')
with open('temp.txt','w',encoding='utf-8') as fw:
fw.write(info) //将之前的运行信息输出到txt文件。
3. 假如有60台设备的话,依次循环,然后按照设备名称保存运行结果即可。