目的: 每天自动接收附件为excel表格的邮件,里面包含客户端ip地址、客户端mac地址、客户端计算机名、交换机端口、交换机的名字等信息。可以给运维人员带来一些方便,直观的查看那些非法的设备接入交换机的那个端口,方便远程shutdown端口(自动shutdown端口和dhcp拉黑mac地址,还在编写中)。
思路: 1、用python代码抓取交换机的上面的信息,例如客户端的mac地址,交换机端口,并把抓取的信息筛选,存入sqlserver数据库。 2、用powershell抓去dhcp的信息,筛选客户端的mac地址,计算机名信息存入sqlserver数据库。 3、通过python代码,调用sql语句,把输出结果保存到excel表格。 4、通过python代码,发送邮件。 5、linux通过crontab,powershell通过自动任务计划,每天定时执行代码和脚本。代码块1: 抓取交换机信息代码,并保存到本地的txt。
import pexpect
import sys
import datetime
import os
today=datetime.date.today().strftime('%y%m%d')
path = /root/f5/+today#创建文件夹
os.mkdir(path,777)
ip='x.x.x.x'
passwd='^^^^^'
txt='f51fa-x.x.x.x.txt'
name=''#交换机名字
name1=---- more ----
child=pexpect.spawn('telnet %s'%ip)#telnet交换机
fout=open('/root/f5/'+today+'/'+txt,'wb+')#输出结果保存到此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])#命令输出结果如果需要空格翻页
if ( index == 0 ):
child.send( )
else:
child.sendline(quit)#如果还有其它命令可以写在这里
sys.exit() 代码块2: powershell抓取dhcp信息,并输出到数据库。
#数据库配置信息
$database = 'mac'
$server = 'xx'
$username = 'sa'
$password = 'xx'
#powershell 抓取dhcp 可以看网页 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 #这个命令是抓取dhcp服务器 x.x.x.x 的所有信息 只输出ipaddress,clientid,hostname 三列
$dhcpleaseresult1 = get-dhcpserverv4lease -computername x -scopeid y.y.y.y |select-object ipaddress,clientid,hostname
#抓取dhcp服务器x(名字或者ip),y.y.y.y作用域的信息,只输出ipaddress,clientid,hostname三列
#创建连接对象
$sqlconn = new-object system.data.sqlclient.sqlconnection
#使用账号连接mssql
$sqlconn.connectionstring = data source=$server;initial catalog=$database;user id=$username;pwd=$password
#打开数据库连接
$sqlconn.open()
#清空数据库里dhcplease记录
$sqlcmd = $sqlconn.createcommand()
$sqlcmd.commandtext = 'truncate table [mac].[dbo].[dhcpf51f]' #数据库表要提前建立好
$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()
}
#
#关闭数据库连接
$sqlconn.close()
exit 代码块3: 把txt文档截取需要的信息,输出到数据库。
import os
import sys
import pymssql
import datetime
#数据库信息
host = 'x.x.x.x'
user = 'sa'
pwd = 'x.x.x.x'
db = 'mac'
#登录数据库,并清空[macf51f]表的内容
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]#数据库表要提前建好
cur.execute(sqls)
conn.commit()
conn.close()
today=datetime.date.today().strftime('%y%m%d')
path = /root/f5/+today
list1=os.listdir(path)#读取文件夹下所有txt文件,注意不要放其它文档,否则需要写判定语句。
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语句插入数据,并命名列
print (sqls)
cur.execute(sqls1)
conn.commit()
conn.close()
for txt in list1:
file = open('%s/%s'%(path,txt),'r+')#打开文件夹下的所有文档
name = txt[:-4]
print(txt)
print(name)
for line in file.readlines():
if 'learned' in line:
if 'more'in line:#截取mac地址,由于dhcp拉出来的mac格式为xx-xx-xx-xx-xx-xx,所以我门要把交换机macxxxx-xxxx-xxxx格式改为统一的
#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: 抓取两个表中mac地址一样的信息,并串接成一个表,并做成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')#设置列头的名字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口是上联口 排除
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 ('创建excel文件完成!')
workbook.save('/root/f5/%sf51fmac.xls'%today)#保存excel 代码块5: 发送邮件代码
#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():
#创建一个带附件的实例
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)#群发需要增加的,隐藏收件人不需要此行,直接调用msg_to就可以
server = smtplib.smtp()
server.connect('10.17.37.96',25)#smtp服务器地址
#server.connect('xx.quantacn.com',25)#需要认证的邮件服务器
#server.login('xx@xx.com','xxxxxxx') #xxx为用户名,xxxxx为密码
#server.sendmail(msg['from'], msg['to'],msg.as_string()) 单独一个收件人
server.sendmail(msg['from'], msg['to'].split(','), msg.as_string())#收件人为多个
#server.sendmail(msg['from'], msg_to, msg.as_string())
server.quit()
return '发送成功'
print (sendmail())定期的任务计划: 1、powershell通过windwos服务器的任务计划每天自动更新dhcp的信息
2、linux服务器通过crontab命令 定制python代码的任务计划
成果:
总结: 后期会实现异常端口自动shutdown,和异常客户端dhcp拉黑mac地址。
HNS 2023 | 华为安全走进千岛之都,于“椰城”共话安全!
雷达物位计的安装说明
Prophesee将推出带有STM32微控制器的GenX320
中国无人机巨头大疆在美国定价和供应进行了重大调整
智能家居会受5G怎样的影响
如何使用Python对网络设备进行运维?
医疗科技时代来临 美国XNUO心诺重点在于放心医疗
槽型光电开关的工作原理/测试方法/典型应用/优势特点
人和人工智能最大的区别
整流桥整流后的波形是什么 整流桥出来的电压怎么稳定
5G网络时代近在咫尺_该攒钱买5G手机了
魅族MX7什么时候上市?全面屏+侧面指纹识别,拍照碾压小米mix2,你选谁?
合理选择高速ADC实现欠采样
洗衣机脱水桶敲缸的巧修
企业电力运维无人值守降本方案说明
VR眼镜,虚拟现实设备有辐射吗?对人眼伤害有多大?
华为马海旭::对外提供鲲鹏处理器主板并优先支持合作伙伴
京东方全球电视面板出货量首次超越LGD 跃居全球第一
Apollo自动驾驶出租车服务即将在长沙开放试运营
人工智能以消除我们招聘过程中的偏见了吗?