代码块3:
把txt文档截取需要的信息,输出到数据库。
import osimport sysimport pymssqlimport 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/"+todaylist1=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 pymssqlimport xlwtimport datetimeworkbook = xlwt.Workbook()today=datetime.date.today().strftime('%Y%m%d')sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True)#定义sheet1sheet1.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 = 1for line in listall: exceladd(line[0],line[1],line[2],line[3],line[4],index) index += 1conn.commit()conn.close()print ('创建excel文件完成!')workbook.save('/root/F5/%sF51FMAC.xls'%today)#保存excel
代码块5:
发送邮件代码
#coding:utf-8from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport smtplibimport datetimefrom email import encodersfrom email.mime.image import MIMEImagefrom email.mime.base import MIMEBasetoday=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地址。
最后
如果对Python感兴趣的话,可以试试我的学习方法以及相关的学习资料
点此免费领取:CSDN大礼包:《python学习路线&全套学习资料》免费分享
一、Python所有方向的学习路线
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
二、Python必备开发工具
三、Python视频合集
观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
四、实战案例
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
五、Python练习题
检查学习结果。
这份完整版的Python全套学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】
先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前在阿里
深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年最新Linux运维全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上运维知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**