導航:首頁 > 編程語言 > python監控

python監控

發布時間:2022-01-12 09:41:34

1. 如何通過python實現實時監控文件

比如要監控nginx的$request_time和$upstream_response_time時間,分析出最耗時的請求,然後去改進代碼,這時就要對日誌進行實時分析了,發現時間長的語句就要報警出來,提醒開發人員要關注,當然這是其中一個應用場景,通過這種監控方式還可以應用到任何需要判斷或分析文件的地方!

2. 怎樣用Python寫一個簡單的監控系統

首先資料庫建表
建立一個資料庫「falcon」,建表語句如下:
CREATE TABLE `stat` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`host` varchar(256) DEFAULT NULL,
`mem_free` int(11) DEFAULT NULL,
`mem_usage` int(11) DEFAULT NULL,
`mem_total` int(11) DEFAULT NULL,
`load_avg` varchar(128) DEFAULT NULL,
`time` bigint(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `host` (`host`(255))
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
首先我們設計一個web服務,實現如下功能:
1. 完成監控頁面展示
2. 接受POST提交上來的數據
3. 提供json數據GET介面
目錄結構如下:
web
├── flask_web.py
└── templates
└── mon.html

flask_web.py

import MySQLdb as mysql
import json
from flask import Flask, request, render_template
app = Flask(__name__)
db = mysql.connect(user="reboot", passwd="reboot123", \
db="falcon", charset="utf8")
db.autocommit(True)
c = db.cursor()

@app.route("/", methods=["GET", "POST"])
def hello():
sql = ""
if request.method == "POST":
data = request.json
try:
sql
= "INSERT INTO `stat`
(`host`,`mem_free`,`mem_usage`,`mem_total`,`load_avg`,`time`)
VALUES('%s', '%d', '%d', '%d', '%s', '%d')" % (data['Host'],
data['MemFree'], data['MemUsage'], data['MemTotal'], data['LoadAvg'],
int(data['Time']))
ret = c.execute(sql)
except mysql.IntegrityError:
pass
return "OK"
else:
return render_template("mon.html")

@app.route("/data", methods=["GET"])
def getdata():
c.execute("SELECT `time`,`mem_usage` FROM `stat`")
ones = [[i[0]*1000, i[1]] for i in c.fetchall()]
return "%s(%s);" % (request.args.get('callback'), json.mps(ones))

if __name__ == "__main__":
app.run(host="0.0.0.0", port=8888, debug=True)

這個template頁面是我抄的highstock的示例,mon.html
簡單起見我們只展示mem_usage信息到頁面上
<title>51reboot.com</title>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$.getJSON('/data?callback=?', function (data) {

// Create the chart
$('#container').highcharts('StockChart', {

rangeSelector: {
inputEnabled: $('#container').width() > 480,
selected: 1
},

title: {
text: '51Reboot.com'
},

series: [{
name: '51Reboot.com',
data: data,
type: 'spline',
tooltip: {
valueDecimals: 2
}
}]
});
});
});
</script>
</head>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/highstock/2.0.4/highstock.js"></script>
<script src="http://code.highcharts.com/moles/exporting.js"></script>

<div id="container" style="height: 400px"></div>
</body>
</html>

web展示頁面完成了,運行起來:
Python flask_web.py 監聽在8888埠上
我們需要做一個Agent來採集數據,並上傳資料庫
moniItems.py
#!/usr/bin/env python
import inspect
import time
import urllib, urllib2
import json
import socket

class mon:
def __init__(self):
self.data = {}

def getTime(self):
return str(int(time.time()) + 8 * 3600)

def getHost(self):
return socket.gethostname()

def getLoadAvg(self):
with open('/proc/loadavg') as load_open:
a = load_open.read().split()[:3]
return ','.join(a)

def getMemTotal(self):
with open('/proc/meminfo') as mem_open:
a = int(mem_open.readline().split()[1])
return a / 1024

def getMemUsage(self, noBufferCache=True):
if noBufferCache:
with open('/proc/meminfo') as mem_open:
T = int(mem_open.readline().split()[1])
F = int(mem_open.readline().split()[1])
B = int(mem_open.readline().split()[1])
C = int(mem_open.readline().split()[1])
return (T-F-B-C)/1024
else:
with open('/proc/meminfo') as mem_open:
a = int(mem_open.readline().split()[1]) - int(mem_open.readline().split()[1])
return a / 1024

def getMemFree(self, noBufferCache=True):
if noBufferCache:
with open('/proc/meminfo') as mem_open:
T = int(mem_open.readline().split()[1])
F = int(mem_open.readline().split()[1])
B = int(mem_open.readline().split()[1])
C = int(mem_open.readline().split()[1])
return (F+B+C)/1024
else:
with open('/proc/meminfo') as mem_open:
mem_open.readline()
a = int(mem_open.readline().split()[1])
return a / 1024

def runAllGet(self):
#自動獲取mon類里的所有getXXX方法,用XXX作為key,getXXX()的返回值作為value,構造字典
for fun in inspect.getmembers(self, predicate=inspect.ismethod):
if fun[0][:3] == 'get':
self.data[fun[0][3:]] = fun[1]()
return self.data

if __name__ == "__main__":
while True:
m = mon()
data = m.runAllGet()
print data
req = urllib2.Request("http://51reboot.com:8888", json.mps(data), {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
print response
f.close()
time.sleep(60)

nohup python moniItems.py >/dev/null 2>&1 & 運行起來

3. python 監控視頻分析

Python有個非常強的庫叫OpenCV,這個庫操作很簡單,可以打開視頻文件做截圖,這個OpenCV庫還提供了兩張圖片的比較功能。
你可以先把視頻每秒截圖一張。
然後只要把連續的截圖後一張對前一張比較,找到差異大的就可以發現圖像有變化

了。

4. python 做監控數據採集,怎麼做.新手請教

這么具體的問題,找通用demo很難啊,個人覺得問題的難點不在Python。
1. 獲取什麼伺服器性能數據和如何獲取,可以請教公司內部運維。
2. 獲取什麼資料庫性能數據和如何獲取,可以請教公司內部DBA。
3. 以上兩點搞定了,才能確定臨時數據存儲結構和最終資料庫表結構。

以上三點是關鍵,Python的事情就簡單多了,提供一種思路:一分鍾一次,實時性不高,每台伺服器用cron部署一個a.py,用於獲取性能數據,在某
一台伺服器有一個b.py,負責獲取所有伺服器a.py產生的數據,然後寫入資料庫;a.py如何上報到b.py取決於你擅長什麼,如果熟悉網路編程,用
a.py做客戶端上報到服務端b.py,如果熟悉shell的文件同步(如rsync),a.py只寫本地文件,b.py調用c.sh(封裝rsync)
拉取遠程文件。

如果解決了您的問題請採納!
如果未解決請繼續追問!

5. python 監控一個文件夾

監控,其實就是周期性的啟動判斷程序。
這判斷程序要看你的具體需求,也就文件怎麼算修改了:判斷文件大小?讀取最後修改時間?還是讀取文件和原文件進行比較?
周期性執行,簡單的就弄個循環就行,這樣程序必須一直運行,不可靠,因為程序可能會被關閉。
所以最好是把程序做成系統服務。
發郵件就比較簡單,網上一堆現成的源碼

6. 有python開發的監控工具嗎

在公司里做的一個介面系統,主要是對接第三方的系統介面,所以,這個系統里會和很多其他公司的項目交互。隨之而來一個很蛋疼的問題,這么多公司的介面,不同公司介面的穩定性差別很大,訪問量大的時候,有的不怎麼行的介面就各種出錯了。
這個介面系統剛剛開發不久,整個系統中,處於比較邊緣的位置,不像其他項目,有日誌庫,還有簡訊告警,一旦出問題,很多情況下都是用戶反饋回來,所以,我的想法是,拿起python,為這個項目寫一個監控。如果在調用某個第三方介面的過程中,大量出錯了,說明這個介面有有問題了,就可以更快的採取措施。
項目的也是有日誌庫的,所有的info,error日誌都是每隔一分鍾掃描入庫,日誌庫是用的mysql,表裡有幾個特別重要的欄位:
有日誌庫,就不用自己去線上環境掃日誌分析了,直接從日誌庫入手。由於日誌庫在線上時每隔1分鍾掃,那我就去日誌庫每隔2分鍾掃一次,如果掃到有一定數量的error日誌就報警,如果只有一兩條錯誤就可以無視了,也就是短時間爆發大量錯誤日誌,就可以斷定系統有問題了。報警方式就用發送郵件,所以,需要做下面幾件事情:
1. 操作MySql。
2. 發送郵件。
3. 定時任務。
4. 日誌。
5. 運行腳本。
明確了以上幾件事情,就可以動手了。
操作資料庫
使用MySQLdb這個驅動,直接操作資料庫,主要就是查詢操作。
獲取資料庫的連接:

def get_con():
host = "127.0.0.1"
port = 3306
logsdb = "logsdb"
user = "root"
password = "never tell you"
con = MySQLdb.connect(host=host, user=user, passwd=password, db=logsdb, port=port, charset="utf8")
return con

從日誌庫里獲取數據,獲取當前時間之前2分鍾的數據,首先,根據當前時間進行計算一下時間。之前,計算有問題,現在已經修改。

def calculate_time():

now = time.mktime(datetime.now().timetuple())-60*2
result = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now))
return result

然後,根據時間和日誌級別去日誌庫查詢數據

def get_data():
select_time = calculate_time()
logger.info("select time:"+select_time)
sql = "select file_name,message from logsdb.app_logs_record " \
"where log_time >"+"'"+select_time+"'" \
"and level="+"'ERROR'" \
"order by log_time desc"
conn = get_con()

cursor = conn.cursor()
cursor.execute(sql)
results = cursor.fetchall()

cursor.close()
conn.close()

return results

發送郵件
使用python發送郵件比較簡單,使用標准庫smtplib就可以
這里使用163郵箱進行發送,你可以使用其他郵箱或者企業郵箱都行,不過host和port要設置正確。

def send_email(content):

sender = "[email protected]"
receiver = ["[email protected]", "[email protected]"]
host = 'smtp.163.com'
port = 465
msg = MIMEText(content)
msg['From'] = "[email protected]"
msg['To'] = "[email protected],[email protected]"
msg['Subject'] = "system error warning"

try:
smtp = smtplib.SMTP_SSL(host, port)
smtp.login(sender, '123456')
smtp.sendmail(sender, receiver, msg.as_string())
logger.info("send email success")
except Exception, e:
logger.error(e)

定時任務
使用一個單獨的線程,每2分鍾掃描一次,如果ERROR級別的日誌條數超過5條,就發郵件通知。

def task():
while True:
logger.info("monitor running")

results = get_data()
if results is not None and len(results) > 5:
content = "recharge error:"
logger.info("a lot of error,so send mail")
for r in results:
content += r[1]+'\n'
send_email(content)
sleep(2*60)

日誌
為這個小小的腳本配置一下日誌log.py,讓日誌可以輸出到文件和控制台中。
# coding=utf-8
import logging

logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)

fh = logging.FileHandler('monitor.log')
fh.setLevel(logging.INFO)

ch = logging.StreamHandler()
ch.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)

logger.addHandler(fh)
logger.addHandler(ch)

所以,最後,這個監控小程序就是這樣的app_monitor.py
# coding=utf-8
import threading
import MySQLdb
from datetime import datetime
import time
import smtplib
from email.mime.text import MIMEText
from log import logger

def get_con():
host = "127.0.0.1"
port = 3306
logsdb = "logsdb"
user = "root"
password = "never tell you"
con = MySQLdb.connect(host=host, user=user, passwd=password, db=logsdb, port=port, charset="utf8")
return con

def calculate_time():

now = time.mktime(datetime.now().timetuple())-60*2
result = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now))
return result

def get_data():
select_time = calculate_time()
logger.info("select time:"+select_time)
sql = "select file_name,message from logsdb.app_logs_record " \
"where log_time >"+"'"+select_time+"'" \
"and level="+"'ERROR'" \
"order by log_time desc"
conn = get_con()

cursor = conn.cursor()
cursor.execute(sql)
results = cursor.fetchall()

cursor.close()
conn.close()

return results

def send_email(content):

sender = "[email protected]"
receiver = ["[email protected]", "[email protected]"]
host = 'smtp.163.com'
port = 465
msg = MIMEText(content)
msg['From'] = "[email protected]"
msg['To'] = "[email protected],[email protected]"
msg['Subject'] = "system error warning"

try:
smtp = smtplib.SMTP_SSL(host, port)
smtp.login(sender, '123456')
smtp.sendmail(sender, receiver, msg.as_string())
logger.info("send email success")
except Exception, e:
logger.error(e)

def task():
while True:
logger.info("monitor running")
results = get_data()
if results is not None and len(results) > 5:
content = "recharge error:"
logger.info("a lot of error,so send mail")
for r in results:
content += r[1]+'\n'
send_email(content)
time.sleep(2*60)

def run_monitor():
monitor = threading.Thread(target=task)
monitor.start()

if __name__ == "__main__":
run_monitor()

運行腳本
腳本在伺服器上運行,使用supervisor進行管理。
在伺服器(centos6)上安裝supervisor,然後在/etc/supervisor.conf中加入一下配置:

復制代碼代碼如下:
[program:app-monitor]
command = python /root/monitor/app_monitor.py
directory = /root/monitor
user = root

然後在終端中運行supervisord啟動supervisor。
在終端中運行supervisorctl,進入shell,運行status查看腳本的運行狀態。
總結
這個小監控思路很清晰,還可以繼續修改,比如:監控特定的介面,發送簡訊通知等等。
因為有日誌庫,就少了去線上正式環境掃描日誌的麻煩,所以,如果沒有日誌庫,就要自己上線上環境掃描,在正式線上環境一定要小心哇~

7. python3監控

1、不知到
2、re.findall(pattern,s)[:3]

8. 如何用 Python 監控系統狀態

建立一個資料庫「falcon」,建表語句如下:
CREATE TABLE `stat` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`host` varchar(256) DEFAULT NULL,
`mem_free` int(11) DEFAULT NULL,
`mem_usage` int(11) DEFAULT NULL,
`mem_total` int(11) DEFAULT NULL,
`load_avg` varchar(128) DEFAULT NULL,
`time` bigint(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `host` (`host`(255))
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

9. 如何使用python腳本實現對windows系統監控

示例:

#!/usr/bin/envpython
#encoding:utf-8

"""
MonitorLog.py

Usage:MonitorLog.py...
Monitorthelogfile

-flogfile
-hhelpinfo

pythonMonitorLog.py-fC:monitor.log

Createdbyzhouboon2011-08-29.
"""

importsys
importos
importgetopt
importsubprocess
importtime
importcodecs
importwinsound

ABSPATH=os.path.dirname(os.path.abspath(__file__))
MONITERCONF='moniter_keyword.txt'#utf8file

defmain():
try:
opts,args=getopt.getopt(sys.argv[1:],'hf:')
exceptgetopt.GetoptError,err:
printstr(err)
print__doc__
return1

path=''
fork,vinopts:
ifk=='-f':
path=v
elifk=='-h':
print__doc__
return0

ifnot(pathandos.path.exists(path)):
print'Invalidpath:%s'%path
print__doc__
return2

#命令行元組
cmd=('tail','-f',path)
print''.join(cmd)
output=subprocess.Popen(cmd,stdout=subprocess.PIPE)

keywordMap={}
#載入監控的關鍵字信息
withcodecs.open(os.path.join(ABSPATH,MONITERCONF),'r','utf8')asf:
lines=f.readlines()
forlineinlines:
line=line.strip()
ifnotline:
continue
keyword,wav=line.strip().split(':')
keywordMap[keyword]=wav

whileTrue:
line=output.stdout.readline()
#processcode,得到輸出信息後的處理代碼
ifnotline:
time.sleep(0.01)
continue
line=line.strip().decode('utf8')
printline
forkeywordinkeywordMap:
ifline.find(keyword)>-1:
winsound.PlaySound(keywordMap[keyword],
winsound.SND_NODEFAULT)
#time.sleep(0.01)
return0

if__name__=='__main__':
sys.exit(main())

10. 如何用python寫監控日誌函數

defwrite_log(username,operation):
'''
寫日誌函數
:paramusername:用戶名
:paramoperation:用戶的操作信息
:return:
'''
w_time=time.strftime('%Y-%m-%d%H%M%S')
withopen('log.txt','a+')asfw:
log_content='%s%s%s '%(w_time,username,operation)
fw.write(log_content)

希望對你有幫助!

閱讀全文

與python監控相關的資料

熱點內容
領克app怎麼綁定車輛別人的車 瀏覽:637
外語教學pdf 瀏覽:38
程序員釋義 瀏覽:249
數控g71編程時應注意什麼 瀏覽:411
捷聯慣導演算法心得 瀏覽:144
c4d命令的理解 瀏覽:568
pdf文檔水印 瀏覽:917
高斯模糊演算法java 瀏覽:354
小學樂高機器人編程作品 瀏覽:522
小猿搜題app怎麼使用 瀏覽:420
內孔左螺紋編程 瀏覽:893
怎麼查找程序員信息 瀏覽:538
adb日誌導出到本地的命令 瀏覽:717
手機微信壓縮包 瀏覽:263
坐高鐵應下什麼app 瀏覽:529
命令行查找文件夾 瀏覽:389
快遞加密個人信息 瀏覽:828
怎麼開對應用的加密 瀏覽:201
備用安卓手機怎麼用 瀏覽:585
數據分析與應用黑馬程序員 瀏覽:485