admin管理员组

文章数量:1530517

首先python没办法直接执行liunx命令,所以我们需要用到commands模块

commands是提供linux系统环境下支持使用shell命令的一个模块

commands.getstatus() 返回执行状态

commands.getoutput() 返回执行结果

commands.getstatusoutput() 返回一个元组,执行状态和执行结果

    import commands
    user = commands.getoutput('ps -ef | grep -v grep | grep user | wc -l')
    print user
    managementP = commands.getoutput('ps -ef | grep -v grep | grep managementP | wc -l')
    print managementP
    gatewayP = commands.getoutput('ps -ef | grep -v grep | grep gatewayP | wc -l')
    print gatewayP
    count = commands.getoutput('ps -ef | grep -v grep | grep count | wc -l')
    print count

下面是项目代码

# -*- coding: UTF-8 -*-

import logging
import json
import schedule
import threading
import time
import socket
import commands

import requests
url = 'xxxxx'
headers = {
    "Metrics-Type": "aiops"
           }
# init lock
lock = threading.Lock()

hostname = socket.gethostname()
# 本机IP
ip = socket.gethostbyname(hostname)
ip_list = [
    'xx',
    'xxx',

]

t = int(round(time.time() * 1000))
data = {}
list_data = []
def business():
    if ip in ip_list:
        if ip == 'xx' or ip == 'xxx':
            gatewayP = commands.getoutput('ps -ef |grep gatewayP |wc -l')
            business_data = {
                "component": 'keyProcess',
                "indicator": "business.server.process.Count",
                "timestamp": t,
                "value": str(gatewayP),
                "tags": {
                    "processKeyword": "gatewayP ",
                    "ip": ip
                }
            }
            list_data.append(business_data)
            json_data = json.dumps(list_data)
            res = requests.post(url=url, data=json_data, headers=headers)
            logging.info(" res%s , data%s" % ( res, json_data ))
    else:
        logging.info(u'ip不在需要获取信息的ip池里')


def run_threaded(job_func):
    job_thread = threading.Thread(target=job_func)
    job_thread.start()


schedule.every(60).seconds.do(run_threaded, business)

while True:
    schedule.run_pending()
    time.sleep(1)

每分钟发送一次进程信息

本文标签: 进程信息Pythonschedule