当前位置: 首页 > news >正文

[Python]—Linux Server 系统监控程序

学习python,写一个小程序加深对Linux和python的理解,程序功能不全,需要逐步完善。

主要功能:

                 1、获取Server Name

                 2、获取操作系统版本信息

                 3、获取CPU硬件信息、CPU的使用率

                 4、获取内存使用信息

                 5、获取相关网络信息

                 6、获取磁盘及分区的相关信息

                 7、获取Server所有的用户名

                 8、获取服务器开机时间、运行时间相关信息

                 9、获取运行队列负载信息

                 10、获取系统进程总数、占用CPU最大的进程、占用内存最大的进程

                 11、获取登陆用户的信息

                 12、解析命令行,将输出导入到文件中保存(重定向输出)



说明:需要自己安装一个psutil包,功能很强大,但是在在本程序中主要还是自己实现为主,仅仅用来获取了一个准确的CPU利用率。

文件名:ServerInfo.py 下载

#!/usr/bin/env python
#coding=utf-8

import os
import re
import socket
import fcntl
import struct
import platform
import sys
import getopt,pwd
import psutil   #需要自己安装
from collections import OrderedDict


def serverName():
    """
    print the hostname information
    """
    sys=os.name
    if sys=='posix':
        name=os.popen('hostname').read().split('\n')[0]
        str="SERVER NAME"
        print '%-15s: %s' %(str,name)
    else:
        return


def sysInfo():
    """
    print the system platform information
    """
    str='SYSTEM VERSION'
    print '%-15s: %s' %(str,platform.platform().strip())


def cpu():
    """
    print the cpu infomation
    """
    cpu=open('/proc/cpuinfo','r')
    lines=cpu.readlines()
    for line in lines:
        model=re.match("model name.*$",line)
        cache=re.match("cache size.*$",line)
        if type(model).__name__!='NoneType':
            Str="CPU TYPE"
            print "%-15s: %s" %(Str,model.group().split(":")[1].strip())
        if type(cache).__name__!='NoneType':
            Str="CPU CACHE"
            print "%-15s: %s" %(Str,cache.group().split(":")[1].strip())
    def get_cpu_percent(interval=1):
        return psutil.cpu_percent(interval=1)
    Str='CPU PERCENT'
    print '%-15s: %s' %(Str,str(get_cpu_percent())+'%')

def mem():
    """
    print the memory information
    """
    meminfo=OrderedDict()
    mem=open('/proc/meminfo','r')
    lines=mem.readlines()
    for line in lines:
        meminfo[line.split(':')[0]]=line.split(":")[1].strip()
    str='TOTAL MEMORY'
    print "%-15s: %s" %(str,meminfo['MemTotal'])
    str='FREE MEMORY'
    print "%-15s: %s" %(str,meminfo['MemFree'])


def networkInfo():
    """
    print the network information
    """
    def get_ip_address(ifname):
            s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
            return socket.inet_ntoa(fcntl.ioctl(
                                    s.fileno(),
                                    0x8915, #SIOCGIFADDR
                                    struct.pack('256s',ifname[:15])
                                    )[20:24])
    interfaces=OrderedDict()
    dict={}
    f=os.popen("ifconfig | grep  'HWaddr' |grep -v '127.0.0.1' |awk '{print $1\",\"$NF}'")
    for ifn in f.readlines():
        ifname=ifn.split(",")[0].strip()
        ifmac=ifn.split(",")[1].strip()
        ipaddr=get_ip_address(ifname)
        interfaces[ifname]=(ifmac,ipaddr)
    for ifn in interfaces:
        print "%-15s: MACaddr %s IPaddr %s" %(ifn.upper(),interfaces[ifn][0],interfaces[ifn][1])
    
    
def diskInfo():
    """
    print the disk information
    """
    def disk_fs_usage(path):
        """
        return total/used/free space info for a filesystem
        """
        fs=os.statvfs(path)  #https://docs.python.org/2/library/statvfs.html
        total=fs.f_frsize*fs.f_blocks
        free=fs.f_frsize*fs.f_bfree
        used=fs.f_frsize*(fs.f_blocks-fs.f_bfree)
        return {
                'total':int(float(total)/1024/1024),
                'used':int(float(used)/1024/1024),
                'free':int(float(used)/1024/1024)}

    f=open('/proc/mounts','r')
    mounts=f.readlines()
    fsInfo={}
    for mount in mounts:
        if mount.startswith('/dev/'):
            mount=mount.split()
            dev=mount[0]
            target=mount[1]
            usageDict=disk_fs_usage(target)
            fsInfo[dev]=usageDict
    #print
    Str='DISK INFO(MB)'
    fs1=list(fsInfo)[0]
    print "%-15s: %s %s" %(Str,fs1,str(fsInfo[fs1]).strip('{}').replace("'","").replace(","," ")) 
    for fs in list(fsInfo)[1:]:
       print '%26s %s' %(fs,str(fsInfo[fs]).strip('{}').replace("'","").replace(","," "))


def runTime():
    f=os.popen("date -d \"$(awk -F. '{print $1}' /proc/uptime) second ago\" +\"%Y-%m-%d %H:%M:%S\"")
    starttime=''
    duration=''
    starttime=f.readline().strip()
    f=os.popen("awk -F. '{days=$1/86400;hours=($1%86400)/3600;minutes=($1%3600)/60;seconds=$1%60;printf(\"%ddays,%dhours,%dminutes,%dseconds\",days,hours,minutes,seconds)}' /proc/uptime")
    duration=f.readline().strip()
    Str='START TIME'
    print '%-15s: %s' %(Str,starttime)
    Str='RUN TIME'
    print '%-15s: %s' %(Str,duration)

def loadAverage():
    """
    表示在过去的1、5、15分钟内运行队列中的平均进程数量
    """
    f=os.popen("uptime | awk -F',' '{print $4$5$6}'")
    line=f.readline().strip().split();
    av1=line[2]
    av5=line[3]
    av15=line[4]
    Str='LOAD AVERAGE'
    print '%-15s: %s %s %s' %(Str,av1,av5,av15)



def processInfo():
    pids=[]
    def get_pids():
        f=os.popen('ps aux| grep -v "%MEM"')
        for p in f.readlines():
            p=p.split()
            pid=(p[0],p[1],p[2],p[3],p[-1][:15])
            pids.append(pid)
    
    get_pids()
    def max_mem_proc():
        return sorted(pids,key=lambda k: k[3]) #sort by memory
    def max_cpu_proc():
        return sorted(pids,key=lambda k: k[2]) #sort by cpu
        
    max_cpu=max_cpu_proc()[-1]
    max_mem=max_mem_proc()[-1]
    Str='TOTAL PROCESSES'
    print '%-15s: %s' %(Str,len(pids))
    Str='MAX CPU PROCESS'
    print '%-15s: USER:%s PID %s CPU:%s MEM:%s COMMAND:%s' \
            %(Str,max_cpu[0],max_cpu[1],max_cpu[2],max_cpu[3],max_cpu[4])
    Str='MAX MEM PROCESS'
    print '%-15s: USER:%s PID %s CPU:%s MEM:%s COMMAND:%s' \
            %(Str,max_mem[0],max_mem[1],max_mem[2],max_mem[3],max_mem[4])




def getusers():
    users=pwd.getpwall()
    #print
    Str='ALL USERS'
    count=0;
    print '%-15s:' %Str,
    for user in users:
        print user.pw_name,
        count+=1
        if count%8==0:
            print ''
            print ' '*16,
    print ''


def loggin():
    f=os.popen("who |grep -v '(:0.*)'")
    Str='LOGGIN USERS'
    print '%-15s: %s' %(Str,f.readline().strip()) 
    for line in f.readlines():
        print ' '*16,
        print line.strip()


class RD_OUTPUT:
    def rd_output_begin(self,filename):
        self.output=open(os.path.join(os.getcwd(),filename),'w')
        sys.stdout=self.output

    def rd_output_end(self):
        sys.stdout=sys.__stdout__  
        self.output.close()
    

class cmd_line:
    def __usage(self):
        print 'usage:ServerInfo.py [-h] [-f]\n'
        print 'Linux Server Usage Monitor'
        print 'optional arguments:'
        print '   -h --help     help information' 
        print '   -f --file=    outputfile'

    def __init__(self):
        try:
            opts,args=getopt.getopt(sys.argv[1:],"hf:",["help","file="])
        except getopt.GetoptError:
            print 'Error:unrecognized arguments!'
            print 'Please execute "ServerInfo.py --help" to get more information!'
            self.__usage()
            sys.exit()
        
        self.filename="ServerInfo.txt"
        for op,value in opts:
            if op in ('-f','--file='):
                self.filename=value
            if op in ('-h','--help'):
                self.__usage()
                sys.exit()
    


if __name__=='__main__':
    arguments=False
    if len(sys.argv)>1:
        arguments=True
    if  arguments:    
        cmd=cmd_line()
        out=RD_OUTPUT()
        out.rd_output_begin(cmd.filename)
    
    serverName()
    runTime()
    sysInfo()
    cpu()
    mem()
    networkInfo()
    diskInfo()
    processInfo()
    loadAverage()
    getusers()
    loggin()

    if arguments:
        out.rd_output_end()
执行结果:

1、输出到屏幕上:


2、输出到文件中:


相关博客:

load average 相关:http://www.51testing.com/html/85/132585-804084.html

相关文章:

  • .NET 4.0中使用内存映射文件实现进程通讯
  • 中国移动短信指令大全
  • SQLServer中的循环批处理
  • IT市场10大趋势!
  • 关于Oracel 10g http://ip:1158/em 的问题
  • 18句话入门SQLServer XML
  • 移动商务潜力无穷
  • 一道可以成为.NET面试“必杀题”的“简单问题”
  • Linux 简单的网络配置练习一
  • 解决Ubuntu 9.04 耳机有声音但外放无声问题
  • IPv4和IPv6比特转发率和包转发率的关系
  • [LeetCode]-Pascal's Triangle III 杨辉三角问题
  • 令狐冲和TCP/IP协议的第三层协议的关系
  • [LeetCode]-Spiral Matrix III 螺旋矩阵
  • 蓝牙3.0+HS规范正式公布 携手802.11大提速
  • CEF与代理
  • CSS 三角实现
  • echarts花样作死的坑
  • happypack两次报错的问题
  • Java的Interrupt与线程中断
  • leetcode378. Kth Smallest Element in a Sorted Matrix
  • MYSQL 的 IF 函数
  • Netty源码解析1-Buffer
  • nfs客户端进程变D,延伸linux的lock
  • node.js
  • python 学习笔记 - Queue Pipes,进程间通讯
  • React16时代,该用什么姿势写 React ?
  • React-生命周期杂记
  • Redis提升并发能力 | 从0开始构建SpringCloud微服务(2)
  • windows下使用nginx调试简介
  • 从@property说起(二)当我们写下@property (nonatomic, weak) id obj时,我们究竟写了什么...
  • 从零开始的无人驾驶 1
  • 读懂package.json -- 依赖管理
  • 精益 React 学习指南 (Lean React)- 1.5 React 与 DOM
  • 漫谈开发设计中的一些“原则”及“设计哲学”
  • 小程序开发之路(一)
  • 中文输入法与React文本输入框的问题与解决方案
  • ​HTTP与HTTPS:网络通信的安全卫士
  • (2)Java 简介
  • (C语言)共用体union的用法举例
  • (Redis使用系列) SpringBoot 中对应2.0.x版本的Redis配置 一
  • (分布式缓存)Redis持久化
  • (附源码)基于SpringBoot和Vue的厨到家服务平台的设计与实现 毕业设计 063133
  • (三) diretfbrc详解
  • (十六)Flask之蓝图
  • (万字长文)Spring的核心知识尽揽其中
  • .NET 4.0中的泛型协变和反变
  • .NET Core 成都线下面基会拉开序幕
  • .NET Core 项目指定SDK版本
  • .NET/C# 如何获取当前进程的 CPU 和内存占用?如何获取全局 CPU 和内存占用?
  • .NET/C# 使用 #if 和 Conditional 特性来按条件编译代码的不同原理和适用场景
  • .NET版Word处理控件Aspose.words功能演示:在ASP.NET MVC中创建MS Word编辑器
  • .NET开源项目介绍及资源推荐:数据持久层 (微软MVP写作)
  • @ConfigurationProperties注解对数据的自动封装
  • @拔赤:Web前端开发十日谈