利用python为运维人员写一个监控脚本

yipeiwu_com5年前Python基础

前言:

一直想写一个监控方面的脚本,然后想到了运维这方面的,后来就写了个脚本,下面话不多说了,来一起看看详细的介绍吧。

准备:

psutil模块(基本使用方法可以参考这篇文章:/post/65044.htm

正文:

import os
import time
import re
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import socket
import psutil
while True:
 def jianca():
 print('[+]Write a port to a file')
 querys=os.popen('netstat -an').read()
 wsd=open('netstat.txt','w')
 wsd.write(querys)
 wsd.close()
 jianca()
 
 def swsd():
 global usd,ow
 wsd=open('netstat.txt','r')
 swd=wsd.read()
 odf=re.findall('(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d):(3389)',swd)
 usd=odf[0]
 print('[+]Query the IP address of a remote connection')
 df=usd[0],usd[1],usd[1],usd[3]
 wdst=".".join(df)
 ow=wdst+":"+usd[4]
 print(usd[0],'.',usd[1],'.',usd[2],'.',usd[3]+":",usd[4])
 swsd()
 
 def ipdw():
 global wdf,ip,timsd
 s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
 dw=s.connect(('8.8.8.8',80))
 ip=s.getsockname()[0]
 print('[+]loacl IP:',ip)
 wdf=os.popen('tasklist').read()
 timsd=time.strftime('%Y-%m-%d',time.localtime(time.time()))
 ipdw()
 
 def yunwei():
 global cput,cp
 cput=psutil.cpu_times()
 cp=psutil.disk_io_counters()
 yunwei()
 
 def stm():
 serder="搜狐邮箱@sina.cn"
 revw="收件箱@qq.com"
 zhengwen='[+]Query the IP address of a remote connection''{}\n' \
  '[+]loacl IP:{}\n' \
  '[+]A program running in the background:{}\n' \
  '[+]The user / system / idle time of statistical CPU:{}\n' \
  '[+]Disk I/O usage{}\n' \
  '[+]Last send time:{}\n' .format(ow,ip,wdf,cput,cp,timsd)
 msg=MIMEText(zhengwen)
 msg['From']=Header('你的搜狐邮箱@sina.cn')
 msg['TO']=Header('收件箱@qq.com','utf-8')
 sub="实时监控"
 msg['subject']=Header(sub,'utf-8')
 try:
  smtp=smtplib.SMTP()
  smtp.connect('smtp.sina.cn',25)
  smtp.login('搜狐邮箱@sina.cn','登录密码')
  smtp.sendmail(serder,revw,msg.as_string())
  print('[+]发送出')
 except Exception as g:
  print('[-]发送失败,原因:',g)
 stm()
 
 time.sleep(3600)

实现原理:首先获取端口状态,然后写人一个txt用正则提取出想要的IP和端口。

然后获取正在后台运行的程序。在获取CPU和磁盘I/O的内存,然后通过邮箱发送‘

到指定收件箱。

运行截图:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

Python 中字符串拼接的多种方法

python拼接字符串一般有以下几种方法: ①直接通过(+)操作符拼接 s = 'Hello'+' '+'World'+'!' print(s) 输出结果: Hello Worl...

python的pdb调试命令的命令整理及实例

python的pdb调试命令的命令整理及实例 一、命令整理 pdb调试命令 完整命令 简写命令 描述...

python数据处理 根据颜色对图片进行分类的方法

python数据处理 根据颜色对图片进行分类的方法

前面一篇文章有说过,利用scrapy来爬取图片,是为了对图片数据进行分类而收集数据。 本篇文章就是利用上次爬取的图片数据,根据图片的颜色特征来做一个简单的分类处理。 实现步骤如下: 1:...

python调用matlab的m自定义函数方法

项目信号处理和提取部分用到了matlab,需要应用到工程中方便研究。用具有万能粘合剂之称的“Python”。具体方法如下: 1.python中安装mlab 下载https://pypi...

Python基础中所出现的异常报错总结

Python基础中所出现的异常报错总结

今天我们来探索python中大部分的异常报错 首先异常是什么,异常白话解释就是不正常,程序里面一般是指程序员输入的格式不规范,或者需求的参数类型不对应,不全等等。 打个比方很多公司年终...