最新文章:

首页 运维技术

python检查linux正在运行的服务

发布时间:2017年10月27日 评论数:抢沙发 阅读数:5260

    一、背景

            最近有一项任务,统计服务器的服务,最为一个攻城狮来讲,这是工作中的常事,也是必须去做的,也是为了尽快熟悉业务,但是问题来了,一台一台的去统计这可难倒我了,能不能我脚本解决呢?shell?Python?既然学习了python何不用python直接搞定呢,于是我就想尝试用Python,我尝试了Python3没搞定发现python2里面有个commands模块,于是就这样开始了。。。。。。

             在开始之向大家介绍一个模块,commands模块,commands模块是Python的内置模块,他共有三个函数,使用help(commands)可以查看到。

    Python
    Help on module commands: NAME
        commands - Execute shell commands via os.popen() and return status, output. FILE /usr/lib64/python2.7/commands.py
    
    DESCRIPTION
        Interface summary: import commands
        
               outtext = commands.getoutput(cmd) (exitstatus, outtext) = commands.getstatusoutput(cmd) outtext = commands.getstatus(file) # returns output of "ls -ld file" A trailing newline is removed from the output string. Encapsulates the basic operation: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') text = pipe.read() sts = pipe.close() [Note: it would be nice to add functions to interpret the exit status.] FUNCTIONS
        getoutput(cmd) Return output (stdout or stderr) of executing cmd in a shell. getstatus(file) Return output of "ls -ld <file>" in a string. getstatusoutput(cmd) Return (status, output) of executing cmd in a shell. DATA
        __all__ = ['getstatusoutput', 'getoutput', 'getstatus']

    1、 commands.getstatusoutput(cmd)返回一个元组(status,output) ,status代表的shell命令的返回状态,如果成功的话是0;output是shell的返回的结果

    Python
    [root@YoungCheung test]# python Python 2.7.5 (default, Sep 15 2016, 22:37:39) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
    Type "help", "copyright", "credits" or "license" for more information. >>> import commands >>> help(commands) >>> import commands >>> status,output = commands.getstatusoutput("ls") >>> print status 0 >>> print output
    a.py
    hello_world.go
    test.py
    test.sh

    2、返回命令ls -ld file执行结果

    Python
    >>> status=commands.getstatus('test.sh') >>> print status -rw-r--r-- 1 root root 2608 Mar 28 09:56 test.sh

    3、判断shell命令输出内容

    Python
    >>> print commands.getoutput("ls") a.py
    hello_world.go
    test.py
    test.sh

    接下来我们回到最开始的问题上,如何使用python并且用这个命令输出运行服务的name && port 

    二、code

    Python
    [root@YoungCheung test]# cat check_service.py  #!/usr/bin/python # coding=utf-8 import commands ##########返回命令执行结果 def getComStr(comand): try: stat, proStr = commands.getstatusoutput(comand) except: print "command %s execute failed, exit" % comand # 将字符串转化成列表 # proList = proStr.split("\n") return proStr ##########获取系统服务名称和监听端口 def filterList(): tmpStr = getComStr("sudo netstat -tpln") tmpList = tmpStr.split("\n") del tmpList[0:2] newList = [] for i in tmpList: val = i.split() del val[0:3] del val[1:3] # 提取端口号 valTmp = val[0].split(":") val[0] = valTmp[-1] # 提取服务名称 valTmp = val[1].split("/") val[1] = valTmp[-1] if val[1] != '-' and val not in newList: newList.append(val) return newList def main(): netInfo = filterList() # 格式化成适合zabbix lld的json数据 json_data = "{\n" + "\t" + '"data":[' + "\n" # print netInfo for net in netInfo: if net != netInfo[-1]: json_data = json_data + "\t\t" + "{" + "\n" + "\t\t\t" + '"{#PPORT}":"' + str( net[0]) + "\",\n" + "\t\t\t" + '"{#PNAME}":"' + str(net[1]) + "\"},\n" else: json_data = json_data + "\t\t" + "{" + "\n" + "\t\t\t" + '"{#PPORT}":"' + str( net[0]) + "\",\n" + "\t\t\t" + '"{#PNAME}":"' + str(net[1]) + "\"}]}" print json_data if __name__ == "__main__": main()

    输出结果:

    Python
    [root@YoungCheung test]# python check_service.py  { "data":[ { "{#PPORT}":"3690", "{#PNAME}":"svnserve"}, { "{#PPORT}":"139", "{#PNAME}":"smbd"}, { "{#PPORT}":"80", "{#PNAME}":"nginx:"}, { "{#PPORT}":"81", "{#PNAME}":"httpd"}, { "{#PPORT}":"210", "{#PNAME}":"sshd"}, { "{#PPORT}":"443", "{#PNAME}":"nginx:"}, { "{#PPORT}":"445", "{#PNAME}":"smbd"}, { "{#PPORT}":"10050", "{#PNAME}":"zabbix_agentd"}, { "{#PPORT}":"10051", "{#PNAME}":"zabbix_server"}, { "{#PPORT}":"9000", "{#PNAME}":"php-fpm:"}, { "{#PPORT}":"3306", "{#PNAME}":"mysqld"}]},
二维码加载中...
本文作者:Mr.linus      文章标题: python检查linux正在运行的服务
本文地址:http://www.90qj.com/450.html  本文已经被百度收录,点击查看详情
版权声明:若无注明,本文皆为“挨踢 Blog”原创,转载请保留文章出处。
挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论