2017-04-07 43 views
0

我已經學會了&試圖在我的下面的代碼中創建兩個函數,其中第一個函數設計用來檢查各種進程狀態如ntp,nscd等。 現在,在執行腳本時,call_function不會給出正確的進程狀態,並且只會爲每個服務返回例如NTP Service is Not Running On the host。而爲FS使用創建的第二功能fs_function正在正常工作。我的call_function不能正常工作正確使用if if else python 2.6

你們可以建議,我在這裏做什麼錯誤.. 下面是代碼..

#!/usr/bin/python 
import subprocess 
import socket 
threshold = 9 
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) 

ps_ntp = call_function("ntp") 
ps_nscd = call_function("nscd") 
ps_mail = call_function("sendmail") 
ps_altris = call_function("aex-plug") 
ps_automnt = call_function("automount") 

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

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

if ps_mail == 0: 
    print "Service Status: Sendmail Service is Running On the host" , hst_name 
else: 
    print "Service Status: Sendmail Service is Not Running" , hst_name 

if ps_altris == 0: 
    print "Service Status: Altris Service is Running On the host" , hst_name 
else: 
    print "Service Status: Altris Service is Not Running On the host" , hst_name 

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

####### Fucntion to Check the File-system thereshold Status ############# 

def fs_function(usage): 
    return subprocess.Popen(['df', '-h', usage], stdout=subprocess.PIPE) 

rootfs = fs_function("/") 
varfs = fs_function("/var") 

output = rootfs.communicate()[0].strip().split("\n") 
for x in output[1:]: 
    if int(x.split()[-2][:-1]) >= threshold: 
     print "Service Status: Filesystem For Root(/) is more than 90% On the Host" , hst_name 
    else: 
     print "Service Status: Filesystem For Root(/) is Normal on The Host", hst_name 

output = varfs.communicate()[0].strip().split("\n") 
for x in output[1:]: 
    if int(x.split()[-2][:-1]) >= threshold: 
     print "Service Status: Filesystem For /var is more than 90% On the Host" , hst_name 
    else: 
     print "Service Status: Filesystem For /var is Normal on The Host", hst_name 
+0

的'grep的service'在你的字符串不使用'service'變量。你告訴'grep'去尋找文字'service',而不是'ntp'或'nscd'或其他東西。 – user2357112

+0

請編輯你的問題到一個[最小,完整和可驗證的例子](https://stackoverflow.com/help/mcve),特別強調_minimum_ ..另外,請注意,使用'shell = True'是一個衆所周知的安全隱患 – Montmons

+0

@ SB87,當然,我會照顧。 – krock1516

回答

1

使用此字符串格式化方法:

return subprocess.call('ps -e | grep %s > /dev/null 2>&1' % service, shell=True) 
+0

我會檢查建議的更改並恢復您的狀態。 – krock1516

+0

@JacobIRR .....字符串格式真的很好! – krock1516