python 服務器監控

#!/usr/bin/python

# coding=utf-8

import commands
import sys

import socket
def isPortAlive(port):
      sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      try:
         sk.connect((sys.argv[0], port))
         sk.close()
         return True
      except Exception, ex:
         sk.close()
         return False

                #get cpu load
cpucmd = 'uptime'
cpuresult = commands.getstatusoutput(cpucmd)
cpuhelp = cpuresult[1].split(':')[-1].split(',')[1].strip()
cpuload = float(cpuhelp)
                    #print "cpu info:",cpuload
        
                     #get mem used
memcmd = 'free -m'
memresult = commands.getstatusoutput(memcmd)
memtotal = float(memresult[1].split('\n')[1].split(':')[1].split()[0].strip())
memused = float(memresult[1].split('\n')[2].split(':')[1].split()[0].strip()) / memtotal * 100
        
                    #print "memory info:",memused
                    #get io of disk
diskcmd = 'iostat -d -k -t 3 2'
                    #cmd = 'sar -d 1 10'  
diskresult = commands.getstatusoutput(diskcmd)
diskhelp = diskresult[1].split('kB_wrtn')[-1].strip().split('\n')
disksum = 0.0
for h in diskhelp:
    disksum = disksum + float(h.split()[-2]) + float(h.split()[-1])

                    #get io of if
netcmd = 'ifstat -T 1 1' 
netresult = commands.getstatusoutput(netcmd)
                    #print "netresult:",netresult
nethelp = netresult[1].split('\n')[-1].split()
netsum = float(nethelp[-2].strip()) + float(nethelp[-1].strip())
a=0
if isPortAlive(9898):
   a=1
   
print str(cpuload)+","+str(memused)+","+str(disksum)+","+str(netsum)+","+str(a);
相關文章
相關標籤/搜索