客戶端腳本:
端腳本:
- - coding:utf-8 - -
import io
import os
import sys
import time
import datetime
import socket
import commands
import logging
from logging import handlers
import psutil
import struct
import fcntl
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')
class Logger(object):
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL
} # 日志級別關(guān)系映射
def init (self,logname, level='info', when='D', backCount=10, fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
CURRENT_DIR = os.path.dirname(file)
LOG_FILE = os.path.abspath(os.path.join(CURRENT_DIR, logname))
self.logger = logging.getLogger(LOG_FILE)
format_str = logging.Formatter(fmt) # 設(shè)置日志格式
self.logger.setLevel(self.level_relations.get(level)) # 設(shè)置日志級別
sh = logging.StreamHandler() # 往屏幕上輸出
sh.setFormatter(format_str) # 設(shè)置屏幕上顯示的格式
th = handlers.TimedRotatingFileHandler(
filename=LOG_FILE, when=when, backupCount=backCount, encoding='utf-8') # 往文件里寫入#指定間隔時間自動生成文件的處理器
#實例化TimedRotatingFileHandler
#interval是時間間隔,backupCount是備份文件的個數(shù),如果超過這個個數(shù),就會自動刪除,when是間隔的時間單位,單位有以下幾種:
S 秒
M 分
H 小時、
D 天、
W 每星期(interval==0時代表星期一)
midnight 每天凌晨
th.setFormatter(format_str) # 設(shè)置文件里寫入的格式
#self.logger.addHandler(sh) # 把對象加到logger里
if not self.logger.handlers:
self.logger.addHandler(th)
class clientMonitor(object):
#獲取指定網(wǎng)卡ip
def getIpAddress(self,dev):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
a = s.fileno()
b = 0x8915
c = struct.pack('256s', dev[:15])
res = fcntl.ioctl(a, b, c)[20:24]
return socket.inet_ntoa(res)
#獲取網(wǎng)絡(luò)的使用情況 ,取的是eth0的發(fā)送和收取的總字節(jié)數(shù)
#readNetInfo('eth0')
def readNetInfo(self,dev):
f = open('/proc/net/dev')
lines = f.readlines()
f.close()
res = {'in':0, 'out':0}
for line in lines:
if line.lstrip().startswith(dev):
for centos
line = line.replace(':', ' ')
items = line.split()
res['in'] = long(items[1])#/1024
res['out'] = long(items[len(items)/2 + 1])#/1024
return res
def readNetInfo_new(self,dev):
res = {'in':0, 'out':0}
res['in'] = psutil.net_io_counters(pernic=True).get(dev).bytes_recv
res['out'] = psutil.net_io_counters(pernic=True).get(dev).bytes_sent
return res
#磁盤使用率,path:磁盤路徑
def disk_stat(self,path):
hd={}
disk = os.statvfs(path)
percent = (disk.f_blocks - disk.f_bfree) * 100 / (disk.f_blocks -disk.f_bfree + disk.f_bavail) + 1
return percent
def net_loop(self,dev):
#end = {'in':0, 'out':0}
res = self.readNetInfo_new(dev)
#推遲執(zhí)行的秒數(shù)
time.sleep(2)
#new_recv,new_send = get_net_data()
new_res = self.readNetInfo_new(dev)
recv_data = (new_res['in']-res['in'])/1024/1024
send_data = (new_res['out']-res['out'])/1024/1024
print ("recv_data: %s M, send_data: %s M"%(recv_data, send_data))
return recv_data,send_data
def processcheck(self,cmd):
#cmd='ps -aux | sort -k3nr | head -1'
(status,output) = commands.getstatusoutput(cmd)
#Pid= output.split(' ')[6]
log.logger.info('資源占用top:\\n'+output)
#查看占用內(nèi)存最高的進(jìn)程的PID
#ps aux|head -1;ps aux|grep -v PID|sort -rn -k +4|head
#ps -aux | sort -k4nr | head -1 ,-k3 cpu占用最高,-k4 內(nèi)存占用最高
#root 14668 1.9 0.0 90504 3256 ? Ss 4月23 2811:48 /sbin/rngd -f
#索引:-k3 b.split(' ')[6] 28進(jìn)程路徑(/sbin/rngd)
#索引:-k4 b.split(' ')[4]
if name == " main ":
#10分鐘執(zhí)行一次,數(shù)據(jù)上報到服務(wù)端,服務(wù)端負(fù)責(zé)報警
#需要修改的參數(shù):custom,deviceType,netName
custom ='test'
deviceType ='客戶端服務(wù)器'
#網(wǎng)卡名稱
netName = 'ens3f0'
log = Logger('socketclient.logs')
log.logger.info("----start----")
info=clientMonitor()
locatIp = info.getIpAddress(netName)
recv_data,send_data = info.net_loop(netName)
cpuinfo = psutil.cpu_percent(1)
#svmem(total=67268558848, available=32022245376, percent=52.4, used=34601009152, free=29655695360, active=17274105856, inactive=2927910912, buffers=10100736, cached=3001753600, shared=298610688, slab=11243315200)
svmem = psutil.virtual_memory()
meminfo = svmem[2]
disk_root = info.disk_stat('/')
disk_appslog = info.disk_stat('/appslog')
disk_bigdata = info.disk_stat('/bigdata')
#如果CPU或內(nèi)存的占用率大于80%,將占用CPU或內(nèi)存資源最多的進(jìn)程找出來
issendmsg =1
if(cpuinfo>80 or meminfo>80 or disk_root>80 or disk_appslog>80 or disk_bigdata>80 or recv_data>3000 or send_data>3000):
#發(fā)送預(yù)警郵件
sendmsg=locatIp +' 服務(wù)器資源占用高!請檢查!\\n'
sendmsg += "CPU占用:"+str(cpuinfo)+'\\n'
sendmsg += "內(nèi)存占用:"+str(meminfo)+'\\n'
sendmsg += "/目錄占用:"+str(disk_root)+'\\n'
sendmsg += "/appslog目錄占用:"+str(disk_appslog)+'\\n'
sendmsg += "/bigdata目錄占用:"+str(disk_bigdata)+'\\n'
sendmsg += "網(wǎng)卡接收流量:"+str(recv_data)+'M,發(fā)送流量 '+str(send_data)+'M \\n'
#sendmsg += "網(wǎng)卡10秒發(fā)送流量:"+str(send_data)+'\\n'
log.logger.info(sendmsg)
if cpuinfo>80 :
info.processcheck('ps -aux | sort -k3nr | head -10')
if meminfo>80 :
info.processcheck('ps -aux | sort -k4nr | head -10')
issendmsg = 1
else:
#log.logger.info(locatIp+" 正常")
log.logger.info("CPU使用率:"+str(cpuinfo))
log.logger.info("內(nèi)存使用率:"+str(meminfo))
log.logger.info("/目錄使用率:"+str(disk_root))
log.logger.info("/appslog使用率:"+str(disk_appslog))
log.logger.info("/bigdata使用率:"+str(disk_bigdata))
log.logger.info("網(wǎng)卡接收和發(fā)送情況:接收"+str(recv_data) +"M, 發(fā)送 "+str(send_data)+"M")
#Id,custom,deviceType,IP,cpu,mem,disk_root,disk_appslog,disk_bigdata,networkRecv,networkSend,uploadTime,temp2,temp3,temp4
msg = '1'+'|'+custom+'|'+deviceType+'|'+locatIp+'|'+str(cpuinfo)+'|'+str(meminfo)+'|'+str(disk_root)+'|'+str(disk_appslog)+'|'+str(disk_bigdata)+'|'+str(recv_data)+'|'+str(send_data)+'|'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if issendmsg ==1:
ip_port = ('IP',port)
sk = socket.socket()
sk.connect(ip_port)
sk.sendall(msg)
data = sk.recv(1024)
if data=='1':
log.logger.info("本地預(yù)警信息傳輸成功!")
else:
log.logger.info("本地預(yù)警信息傳輸失??!")
sk.sendall('exit')
sk.close()
原文鏈接:https://blog.csdn.net/eagle89/article/details/128579002
-
監(jiān)控
+關(guān)注
關(guān)注
6文章
2162瀏覽量
55041 -
服務(wù)器
+關(guān)注
關(guān)注
12文章
8958瀏覽量
85081
發(fā)布評論請先 登錄
相關(guān)推薦
評論