利用Python自动登录到网络设备,根据回显不同来配置不同的参数,避免简单重复的劳动,提高网络相关工作的效率。本例就可以做到Python登录Router1和Router2,根据lldp读出端口,然后根据Router1和Router2的编号自动在端口上配置地址。两台看不出来优势,两百台优势就杠杠的了。

【网络拓扑】

元进网络自动化(3)---Python自动给网络设备下配置_网络自动化

【打印登录配置过程】

H:\Alphism\venv\Scripts\python.exe "H:/Alphism/Mest Inc/Python_eNSP.py"


 -----------------------------------------------------------------------------      

 User last login information:      

 -----------------------------------------------------------------------------

 Access Type: Telnet      

 IP-Address : 10.0.0.1      

 Time       : 2022-11-12 15:49:48-08:00      

 -----------------------------------------------------------------------------

<Router1>


<Router1>system

Enter system view, return user view with Ctrl+Z.

[Router1]


[Router1]

interface GI0/0/1

[Router1-GigabitEthernet0/0/1]

ip address 100.1.2.1 30

[Router1-GigabitEthernet0/0/1]


 -----------------------------------------------------------------------------      

 User last login information:      

 -----------------------------------------------------------------------------

 Access Type: Telnet      

 IP-Address : 10.0.0.1      

 Time       : 2022-11-12 15:49:50-08:00      

 -----------------------------------------------------------------------------

<Router2>


<Router2>system

Enter system view, return user view with Ctrl+Z.

[Router2]


[Router2]

interface GI0/0/1

[Router2-GigabitEthernet0/0/1]

ip address 100.1.2.2 30

[Router2-GigabitEthernet0/0/1]

IP Config is OK at 2022-11-12-1551


Process finished with exit code 0

【代码实现及注释】

import telnetlib
import re
import time
import socket

class LoginRouter():
def __init__(self, ip='10.0.0.2', port=23, user='mest', pw="mest"):
self.username = user
self.password = pw
self.host = ip
self.port = port
self.router_username_prompt = 'Username:'
self.router_password_prompt = 'Password:'
self.tn = telnetlib.Telnet(host=ip, port=self.port, timeout=1)
self.login()

def write(self, str='#'):
self.tn.write((str + '\n').encode('ascii'))

def read_until(self, str=']', timeout=1):
output = self.tn.read_until(str.encode('ascii'), timeout=3)
return output.decode('utf-8')

def read_all(self):
try:
self.write(']')
output = self.read_until(']')
return output
except socket.timeout:
print('Reading timeout')

# 登陆设备
def login(self):
try:
self.read_until(self.router_username_prompt)
self.write(self.username)
self.read_until(self.router_password_prompt)
self.write(self.password)
print(self.read_until(str='>'))
except:
print("Telnet Failure")

if __name__ == '__main__':
k = 0
j = time.strftime('%Y-%m-%d-%H%M',time.localtime(time.time()))
e = [2,3] #输入设备地址,这里是以10.0.0为默认
while k <= 1:
router = LoginRouter(ip = '10.0.0.'+str(e[k]), port = 23, user = 'mest', pw = 'mest')
router.write(str='display lldp neighbor bri\n')
lldp = router.read_until('>',timeout=20)
interfacet =re.findall(r'\S*GE\S*',lldp)
del interfacet[0:2]
interface= [str(i).replace('E','I') for i in interfacet]
device=re.findall(r'Router\S*',lldp) #获取设备名和端口名两个数组
router.write(str='system\n')
print(router.read_until(']'))
i=0
while i<len(interface)//2: #配置设备IP地址
if device[i][-1]<device[-1][-2]:
router.write(str='interface '+interface[i*2]+'\n')
print(router.read_until(']',timeout=10))
router.write(str='ip address 100.'+device[i][-1]+'.'+device[-1][-2]+'.2 30\n')
print(router.read_until(']',timeout=10))
else:
router.write(str='interface '+interface[i*2]+'\n')
print(router.read_until(']',timeout=10))
router.write(str='ip address 100.'+device[-1][-2]+'.'+device[i][-1]+'.1 30\n')
print(router.read_until(']',timeout=10))
i+=1
k+=1
router.read_all()
print(router.read_all())
print('IP Config is OK at '+str(j))