【實(shí)用】如何使用Python對(duì)網(wǎng)絡(luò)設(shè)備進(jìn)行運(yùn)維?
目的:
每天自動(dòng)接收附件為excel表格的郵件,里面包含客戶端IP地址、客戶端MAC地址、客戶端計(jì)算機(jī)名、交換機(jī)端口、交換機(jī)的名字等信息??梢越o運(yùn)維人員帶來(lái)一些方便,直觀的查看那些非法的設(shè)備接入交換機(jī)的那個(gè)端口,方便遠(yuǎn)程shutdown端口(自動(dòng)shutdown端口和DHCP拉黑MAC地址,還在編寫中)。
思路:
1、用python代碼抓取交換機(jī)的上面的信息,例如客戶端的MAC地址,交換機(jī)端口,并把抓取的信息篩選,存入sqlserver數(shù)據(jù)庫(kù)。
2、用Powershell抓去DHCP的信息,篩選客戶端的MAC地址,計(jì)算機(jī)名信息存入sqlserver數(shù)據(jù)庫(kù)。
3、通過(guò)Python代碼,調(diào)用SQL語(yǔ)句,把輸出結(jié)果保存到excel表格。
4、通過(guò)Python代碼,發(fā)送郵件。
5、linux通過(guò)crontab,Powershell通過(guò)自動(dòng)任務(wù)計(jì)劃,每天定時(shí)執(zhí)行代碼和腳本。
代碼塊1:
抓取交換機(jī)信息代碼,并保存到本地的txt。
import pexpect
import sys
import datetime
import os
today=datetime.date.today().strftime('%Y%m%d')
path = "/root/F5/"+today#創(chuàng)建文件夾
os.mkdir(path,777)
ip='x.x.x.x'
passwd='^^^^^'
txt='F51FA-x.x.x.x.txt'
name=''#交換機(jī)名字
name1="---- More ----"
child=pexpect.spawn('telnet %s'%ip)#telnet交換機(jī)
fout=open('/root/F5/'+today+'/'+txt,'wb+')#輸出結(jié)果保存到此txt
child.logfile = fout
child.expect('Username:')
child.sendline("admin")
child.expect('(?i)ssword:')
child.sendline("%s"%passwd)
child.expect("%s"%name)
child.sendline("dis lldp neighbor-information list")
child.expect("%s"%name)
child.sendline("dis mac-address")
for i in range(10):
index = child.expect([name1,"%s"%name])#命令輸出結(jié)果如果需要空格翻頁(yè)
if ( index == 0 ):
child.send(" ")
else:
child.sendline("quit")#如果還有其它命令可以寫在這里
sys.exit()
代碼塊2:
powershell抓取DHCP信息,并輸出到數(shù)據(jù)庫(kù)。
#數(shù)據(jù)庫(kù)配置信息
$Database = 'MAC'
$Server = 'xx'
$UserName = 'sa'
$Password = 'xx'
#powershell 抓取DHCP 可以看網(wǎng)頁(yè) http://blog.51cto.com/wenzhongxiang/2065645
#讀取DHCPLease記錄
#$DhcpLeaseResult1 = Get-DhcpServerv4Scope -ComputerName x.x.x.x |Get-DhcpServerv4Lease -ComputerName x.x.x.x |Select-Object IPAddress,ClientId,HostName #這個(gè)命令是抓取DHCP服務(wù)器 x.x.x.x 的所有信息 只輸出IPAddress,ClientId,HostName 三列
$DhcpLeaseResult1 = Get-DhcpServerv4Lease -ComputerName x -ScopeId y.y.y.y |Select-Object IPAddress,ClientId,HostName
#抓取DHCP服務(wù)器X(名字或者IP),y.y.y.y作用域的信息,只輸出IPAddress,ClientId,HostName三列
#創(chuàng)建連接對(duì)象
$SqlConn = New-Object System.Data.SqlClient.SqlConnection
#使用賬號(hào)連接MSSQL
$SqlConn.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;user id=$UserName;pwd=$Password"
#打開(kāi)數(shù)據(jù)庫(kù)連接
$SqlConn.open()
#清空數(shù)據(jù)庫(kù)里DHCPLease記錄
$SqlCmd = $SqlConn.CreateCommand()
$SqlCmd.commandtext = 'TRUNCATE TABLE [MAC].[dbo].[DHCPF51F]' #數(shù)據(jù)庫(kù)表要提前建立好
$SqlCmd.ExecuteScalar()
#插入最新的DHCPLease記錄
foreach($x in $DhcpLeaseResult1)
{
Write-Host $x.IPAddress.IPAddressToString,$x.ClientId,$x.HostName
$SqlCmd.commandtext = "INSERT INTO [MAC].[dbo].[DHCPF51F] (IP,MAC,Hostname) VALUES('{0}','{1}','{2}')" -f $x.IPAddress.IPAddressToString,$x.ClientId,$x.HostName
$SqlCmd.ExecuteScalar()
}
#
#關(guān)閉數(shù)據(jù)庫(kù)連接
$SqlConn.close()
Exit
代碼塊3:
把txt文檔截取需要的信息,輸出到數(shù)據(jù)庫(kù)。
import os
import sys
import pymssql
import datetime
#數(shù)據(jù)庫(kù)信息
host = 'x.x.x.x'
user = 'sa'
pwd = 'x.x.x.x'
db = 'MAC'
#登錄數(shù)據(jù)庫(kù),并清空[MACF51F]表的內(nèi)容
conn = pymssql.connect(host=host,user=user,password=pwd,database=db,timeout=1,login_timeout=1,charset="utf8")
cur = conn.cursor()
sqls = "delete from [dbo].[MACF51F]"#數(shù)據(jù)庫(kù)表要提前建好
cur.execute(sqls)
conn.commit()
conn.close()
today=datetime.date.today().strftime('%Y%m%d')
path = "/root/F5/"+today
list1=os.listdir(path)#讀取文件夾下所有txt文件,注意不要放其它文檔,否則需要寫判定語(yǔ)句。
def getid(linea,lineb):
conn = pymssql.connect(host=host,user=user,password=pwd,database=db,timeout=1,login_timeout=1,charset="utf8")
cur = conn.cursor()
sqls1 = "insert into [MACF51F] values('%s','%s','%s')"%(linea,lineb,name)#sql語(yǔ)句插入數(shù)據(jù),并命名列
print (sqls)
cur.execute(sqls1)
conn.commit()
conn.close()
for txt in list1:
file = open('%s/%s'%(path,txt),'r+')#打開(kāi)文件夾下的所有文檔
name = txt[:-4]
print(txt)
print(name)
for line in file.readlines():
if 'Learned' in line:
if 'More'in line:#截取MAC地址,由于dhcp拉出來(lái)的MAC格式為xx-xx-xx-xx-xx-xx,所以我門要把交換機(jī)MACXXXX-xxxx-xxxx格式改為統(tǒng)一的
#linea=(line[43:57]).rstrip()
linea=(line[43:45]+'-'+line[45:48]+line[48:50]+'-'+line[50:53]+line[53:55]+'-'+line[55:57]).rstrip()
lineb=(line[84:107]).rstrip()
else:
#linea=(line[0:15]).rstrip()
linea=(line[0:2]+'-'+line[2:5]+line[5:7]+'-'+line[7:10]+line[10:12]+'-'+line[12:14]).rstrip()
lineb=(line[41:65]).rstrip()
print(linea)
print(lineb)
getid(linea,lineb)
代碼塊4:
抓取兩個(gè)表中MAC地址一樣的信息,并串接成一個(gè)表,并做成excel。
import pymssql
import xlwt
import datetime
workbook = xlwt.Workbook()
today=datetime.date.today().strftime('%Y%m%d')
sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True)#定義sheet1
sheet1.write(0,0,'HotName')#設(shè)置列頭的名字0,0代表 0行 0列
sheet1.write(0,1,'MACAddress')
sheet1.write(0,2,'IPAddress')
sheet1.write(0,3,'Port')
sheet1.write(0,4,'SwitchName')
def exceladd(HotName,MACAddress,IPAddress,Port,SwitchName,index):
sheet1.write(index,0,HotName)
sheet1.write(index,1,MACAddress)
sheet1.write(index,2,IPAddress)
sheet1.write(index,3,Port)
sheet1.write(index,4,SwitchName)
host = 'x.x.x.x'
user = 'sa'
pwd = 'x'
db = 'MAC'
conn = pymssql.connect(host=host,user=user,password=pwd,database=db,timeout=1,login_timeout=1,charset="utf8")
cur = conn.cursor()
sqls ="select Hostname,mac,ip,port,Switchname from [dbo].[MACF51F] join [dbo].[DHCPF51F] on MAC = MACADD where Port<>'GigabitEthernet1/0/24' order by Switchname,Port" #SQL命令 24口是上聯(lián)口 排除
cur.execute(sqls)
listall = cur.fetchall()#抓取sql輸出的每一行信息,并分解保存到excel表中。
index = 1
for line in listall:
exceladd(line[0],line[1],line[2],line[3],line[4],index)
index += 1
conn.commit()
conn.close()
print ('創(chuàng)建excel文件完成!')
workbook.save('/root/F5/%sF51FMAC.xls'%today)#保存excel
代碼塊5:
發(fā)送郵件代碼
#coding:utf-8
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import datetime
from email import encoders
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
today=datetime.date.today().strftime('%Y%m%d')
def sendmail():
#創(chuàng)建一個(gè)帶附件的實(shí)例
msg = MIMEMultipart()
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
file = MIMEBase(maintype, subtype)
file.set_payload(open(r'/root/F5/%sF51FMAC.xls'%today, 'rb').read())
file.add_header('Content-Disposition', 'attachment', filename='%sF51FMAC.xls'%today)
encoders.encode_base64(file)
msg.attach(file)
#加郵件頭
msg_to=['xxx@xxx.com','xx@xxx.com','Klaus.Wang@xx.com','Eric.lai@xx.com']
msg['from'] = 'xxx@xx.com'
msg['subject'] = u"[接入巡檢] %s" %today
msg.attach(MIMEText('接入MAC地址記錄如附件', 'plain', 'utf-8'))
msg['to'] =','.join(msg_to)#群發(fā)需要增加的,隱藏收件人不需要此行,直接調(diào)用msg_to就可以
server = smtplib.SMTP()
server.connect('10.17.37.96',25)#SMTP服務(wù)器地址
#server.connect('xx.quantacn.com',25)#需要認(rèn)證的郵件服務(wù)器
#server.login('xx@xx.com','xxxxxxx') #XXX為用戶名,XXXXX為密碼
#server.sendmail(msg['from'], msg['to'],msg.as_string()) 單獨(dú)一個(gè)收件人
server.sendmail(msg['from'], msg['to'].split(','), msg.as_string())#收件人為多個(gè)
#server.sendmail(msg['from'], msg_to, msg.as_string())
server.quit()
return '發(fā)送成功'
print (sendmail())
定期的任務(wù)計(jì)劃:
1、Powershell通過(guò)windwos服務(wù)器的任務(wù)計(jì)劃每天自動(dòng)更新DHCP的信息
2、linux服務(wù)器通過(guò)crontab命令 定制python代碼的任務(wù)計(jì)劃
成果:
總結(jié):
后期會(huì)實(shí)現(xiàn)異常端口自動(dòng)shutdown,和異??蛻舳薉HCP拉黑MAC地址。
作者:圈圈
歡迎關(guān)注微信公眾號(hào) :釋然IT雜談