需求:登录交换机下指令对回传信息进行抓取写入 CSV文件
#encoding=utf-8
import telnetlib
import re
import datetime,os
def do_telnet(HOST,USERNAME,PASSWORD):
tn = telnetlib.Telnet(HOST, port=23, timeout=10)
tn.set_debuglevel(2)
tn.read_until('Username:')
tn.write(USERNAME+'\n')
tn.read_until('Password:')
tn.write(PASSWORD+'\n')
tn.read_until("F3-3850-TEST>")
tn.write('enable'+'\n')
tn.read_until('Password:')
tn.write(PASSWORD+'\n')
tn.read_until("F3-3850-TEST#")
global msg
msg = ''
space_time = 0
for i in range(3, 13):
tn.write("show ip arp vlan %d" %i + '\n')
while space_time <= 5:
tn.write(' ')
space_time = space_time+1
space_time = 0
tn.write('\n')
tn.write("quit\n")
msg = tn.read_until("F3-3850-TEST#quit\n")
def deal_and_uplog():
#path1 = '\\\\172.24.255.126\\log\\STATIONINFO\\MP\\11\\11\\ON_LINE\\PASS\\%s\\IPINFO %s.csv'%(datatime.datetime.now().strftime('Y%m%d'),datatime.datetime.now().strftime('Y%m%d%H%I%M%S'))
path1= '\\\\172.24.255.126\\log\\IPINFO'
try:
os.makedirs(path1)
except:
pass
path = '%s\\IPINFO_%s.csv'%(path1,datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))
road = path
with open(path,'w') as f:
patt1 = "Protocol,Address,Age (min),Hardware Addr,Type,Interface\n"
f.write(patt1)
patt = r'(\w+)\s+(\d+\.\d+\.\d+\.\d+)\s+(\d+)\s+([a-z0-9]*\.[a-z0-9]*\.[a-z0-9]*)\s+([A-Z]*)\s+(.+)'
with open(path, 'a+') as f:
m = re.findall(patt,msg)
if m is not None:
for i in m:
patt2 = i[0] + ',' + i[1] + ',' + i[2] + ',' + i[3] + ',' + i[4] + ',' + i[5]
f.write(patt2)
if __name__ == "__main__":
HOST = "192.168.xxx.xxx"
USERNAME = 'xxx'
PASSWORD = 'xxx'
do_telnet(HOST,USERNAME,PASSWORD)
deal_and_uplog()