Python添加多项检查在具有返回调用的函数下

问题描述 投票:0回答:1

我有一个下面的代码片段来运行快速健康检查系统和服务,这是正常工作但是,我想包括一个检查elif条件为call_functionps_rpcbind因为截至目前我正在检查rpc服务是否它运行或不简单,在ps -e | grep rpc下检查call_function,我想根据命令rpcinfo -p添加一个条件来交叉验证相同。

我可以在call_function下添加它吗?

import subprocess
import socket
hst_name = (socket.gethostname())
print "HostName:", hst_name
############### Function to Check the Different process & Service Status #########

def call_function(service):
   #return subprocess.call('ps -e | grep service> /dev/null 2>&1', shell=True)
   return subprocess.call('ps -e | grep %s > /dev/null 2>&1' % service, shell=True)
ps_ntp = call_function("ntp")
ps_nscd = call_function("nscd")
ps_mail = call_function("sendmail")
ps_postfix = call_function("qmgr")
#ps_altris = call_function("aex-plug")
ps_automnt = call_function("automount")
ps_rpcbind = call_function("rpc")

if ps_ntp == 0:
    print "Service Status:  NTP is Running on the host", hst_name
else:
   print  "Service Status:  NTP is not Running on the host", hst_name

if ps_nscd == 0:
   print "Service Status:  NSCD is Running on the host", hst_name
else:
   print "Service Status:  NSCD is not Running on the host", hst_name

if ps_rpcbind == 0:
   print "Service Status: Rpcbind is Running on the host", hst_name
else:
   print "Service Status: Rpcbind is not Running on the host", hst_name

if ps_mail == 0:
   print "Service Status:  Sendmail is Running on the host", hst_name
elif ps_postfix == 0:
   print "Service Status:  Postfix  is Running on the host", hst_name
else:
   print "Service Status:  Sendmail is not Running on the host", hst_name

if ps_automnt == 0:
   print "Service Status:  Automount is Running on the host" , hst_name
else:
   print "Service Status:  Automont is not Running on the host" , hst_name

你想要什么:基于rpcinfo -p

if ps_rpcbind == 0:
   print "Service Status: Rpcbind is Running on the host", hst_name
elif ps_rpc == 0:
   print "Service Status: Rpcbind is Running on the host", hst_name
else:
   print "Service Status: Rpcbind is not Running on the host", hst_name

命令rpcinfo -p返回输出以下。

   # rpcinfo -p
   program vers proto   port  service
    100000    4   tcp    111  portmapper
    100000    3   tcp    111  portmapper
    100000    2   tcp    111  portmapper
    100000    4   udp    111  portmapper
    100000    3   udp    111  portmapper
    100000    2   udp    111  portmapper

如果需要任何细节,请告诉我。

python subprocess
1个回答
1
投票

更新

所以根据你的评论,我认为你可以做到以下几点。

if ps_rpcbind == 0:
   print "Service Status: Rpcbind is Running on the host", hst_name
elif not sb.check_call('rpcinfo -p', shell=True, stdout=sb.PIPE)
    print("RPC service is running")
else:
   print "Service Status: Rpcbind is not Running on the host", hst_name

请注意,0作为返回代码意味着服务运行良好,但在python 0False,所以你必须检查not

© www.soinside.com 2019 - 2024. All rights reserved.