作为一名新手python学习者,我创建了以下脚本来检查各种进程和文件系统的用法,我希望以更复杂或最好的方式包装到函数中。
请建议如何做到这一点.. 我的python版本是2.6
#!/usr/bin/python
import subprocess
import socket
THRESHOLD = 90
HST = (socket.gethostname())
print "HostName:", HST
PSNTP = subprocess.call('ps -e| grep ntp > /dev/null 2>&1', shell=True)
if PSNTP == 0:
print "Service Status: NTP Service is Running"
else:
print "Service Status: NTP Service is Running"
PSNSCD = subprocess.call('ps -e | grep nscd > /dev/null 2>&1', shell=True)
if PSNSCD == 0:
print "Service Status: NSCD Service is Running On the host" , HST
else:
print "Service Status: NSCD Service Not is Running", HST
PSMAIL = subprocess.call('ps -e | grep sendmail> /dev/null 2>&1', shell=True)
if PSMAIL == 0:
print "Service Status: Sendmail Service is Running"
else:
print "Service Status: Sendmail is Not Service Not is Running"
PSALTRIS = subprocess.call('ps -e | grep aex-plug > /dev/null 2>&1', shell=True)
if PSALTRIS == 0:
print "Service Status: Altris Service is Running"
else:
print "Service Status: Altris Service Not is Running"
PSAUTMNT = subprocess.call('ps -e| grep automount > /dev/null 2>&1', shell=True)
if PSAUTMNT == 0:
print "Service Status: Automount Service is Running"
else:
print "Service Status: Automont Service Not is Running"
rootfs = subprocess.Popen(['df', '-h', '/'], stdout=subprocess.PIPE)
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 20 % On the Host" , HST
else:
print "Service Status: Filesystem For Root(/) is Normal on The Host", HST
varfs = subprocess.Popen(['df', '-h', '/'], stdout=subprocess.PIPE)
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 20 % On the Host" , HST
else:
print "Service Status: Filesystem For /var is Normal on The Host", HST
答案 0 :(得分:2)
@timgeb有一个非常好的观点。你正在寻找的东西就像谷歌搜索功能一样简单,然后花一些时间阅读。
话虽如此,一些指示,意识到你要求人们在这里的时间,所以你理解礼仪要好得多。首先,你发现了一个问题,似乎没有做过任何研究,至少你没有暗示任何相反的事情。最好提供一些你尝试过的例子让我们知道你的想法,这样我们就可以指出你正确的方向而不是形象地说'#34;我希望我的代码更复杂但是我希望你们所有人为我做的工作"。
话虽如此,这里有一些东西让你去。在功能方面,它是关于编写重复代码一次,这样你就不必一次又一次地执行它。一个简单的例子,你写了" = subprocess.call(' ps -e | grep nscd> / dev / null 2>& 1',shell = True)"好几次,除了nscd,其他一切都保持不变,因此:
def call_function(service):
return subprocess.call('ps -e | grep service > /dev/null 2>&1', shell=True)
PSNTP = call_function("ntp")
PSNSCD = call_function("nscd")
if PSNTP == 0:
........
有意义吗?如果命令中出现了什么" ps -e ......."更改然后您只需要更改一次,而不是搜索整个程序来更改它。