Python collects Linux (Ubuntu environment tested) system Information--CPU, memory, disk, NIC

Source: Internet
Author: User

#!/usr/bin/python# coding:utf-8import osimport jsonimport socketimport psutilclass  host:    _hostname = socket.getfqdn (Socket.gethostname ())       @classmethod     def get_local_addr (CLS):         addr = socket.gethostbyname (Cls._hostname)          return addr     @classmethod     def get_hostname ( CLS):         return cls._hostname    @ Classmethod    def ping (CLS):         result  = os.system ("Ping -c 1 -w 1 %s >/dev/null"  % cls.get_ LOCAL_ADDR ())         if result == 0:             return 1        else:             return 0class cpu:    @ Classmethod    def _get_cpu_load (CLS):         # get cpu 5 minutes load        loadavg  =  "/proc/loadavg"         with open (LOADAVG)  as  f:            con = f.read (). Split ()             return con[1]      @classmethod     def _get_cpu_usage (CLS):         # return a float representing the current system-wide cpu  utilization as a&nbSp;percentage        return psutil.cpu_percent (interval=0.1)      @classmethod     def get_cpu_info (CLS):         cpu = {              "Cpuutil":  cls._get_cpu_load (),              "cpuused":  cls._get_cpu_usage ()         }         return cpuclass Memory:    mem =  Psutil.virtual_memory ()      @classmethod     def _get_mem_total (CLS ):         return cls.mem.total    @ Classmethod    def _get_mem_used (CLS):         return cls.mem.used     @classmethod     def get_mem_info (CLS):         mem = {             " Memused ":  cls._get_mem_used (),            " Memtotal ":  cls._get_mem_total (),        }         return memclass NetworkCard:     @classmethod      def get_card_bytes_info (CLS):         # bytes_ sent        try:             card_ip = []             card_io = []            interface  = []            for k, v in psutil.net_if_ Addrs (). Items ():                 if k not in  ' lo ':                     card_ip.append ({' Name ': k,  ' IP ': v[0].address})             for k, v in  Psutil.net_io_counters (pernic=true). Items ():                 if k not in  ' lo ':                     card_io.append ({' name ':  k,   ' out ': v.bytes_sent,  ' in ':  v.bytes_recv})              for i in range (Len (card_ip)):                 card = {                      ' intname ':  card_io[i][' name '],                      ' IP ':  card_ip[i][' IP '],                      ' out ':  card_io[i][' out '],                      ' in ':  card_io[i][' in ' ]                }                 interface.append (Card)             return interface         except AttributeError as e:             print ("Please use psutil version 3.0 or above") Class Disk:      @classmethod     def get_disk_info (CLS):         disklt = []        for  Disk, sdiskio in psutil.disk_io_counters (Perdisk=true, nowrap=false). Items ():             if disk.startswith (' SD ', ' VD '):                 device =  '/dev/{ } '. Format (disk)                  capacity = psutil.dIsk_usage (device)                  diskdt = {                      "DiskName": device,                      "Total": capacity.total,                       "used": capacity.used,                      "WS": sdiskio.write_merged_count,                      "RS":  sdiskio.read_merged_count,                      "Wiops": sdiskio.write_count,                      "Riops": sdiskio.read_count,                      "RKB":  sdiskio.read_bytes / 1024,                      "WKB": sdiskio.write_bytes / 1024                 }                 disklt.append (DISKDT)          return diskltclass summary:    def  __init__ (self):        self._hostid = 1         Self._groupid = 1        self._hostname = host.get _hostname ()         self._ip = host.get_local_addr ()          self._ping = host.ping ()          self._cpu = cpu.get_cpu_info ()         self . _memory = memory.get_mem_info ()         self._network =  networkcard.get_card_bytes_info ()         self._disk =  Disk.get_disk_info ()     def start_collecting (self):         summary = {              ' HostID ': self._hostid,             ' GroupID ':  self._groupid,             ' hostname ': self._hostname,              ' IP ': self._ip,              ' ping ': self._ping,              ' CPU ': self._cpu,              ' Memory ': self._memory,              ' Network ': self._network,              ' Disk ': self._disk        }         return json.dumps (summary)         if  __name__ ==  ' __main__ ':     c = summary ()      Print (c.start_collecting ())



Python collects Linux (Ubuntu environment tested) system Information--CPU, memory, disk, NIC

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.