2016-09-21 22 views
0

我正在编写一个将基于登录到我的实例的用户数退出的nagios插件。使用python从操作系统读取用户数量

import argparse 
import subprocess 
import os 
import commands 
import sys 

if __name__ == '__main__': 
     parser = argparse.ArgumentParser(description='checks number of logged in users') 
     parser.add_argument('-c','--critical', help='enter the value for critical limit', nargs='?', const=10) 
     parser.add_argument('-w','--warning', help='enter the value for warning limit', nargs='?', const=5) 
     args = parser.parse_args() 
     x= commands.getstatusoutput("users | tr ' ' '\n' | sort -u | wc -l") 
     a= os.popen("users | tr ' ' '\n' | sort -u | wc -l").read() 
     print type(a) 
     print "value of critical is %s" % (args.critical) 
     print a 
     (co, res) = x 
     print "result from command is %s" % (res) 
     print type(res) 
     if a >= args.critical: 
       print "we are critical" 
       sys.exit(2) 
     elif a <= args.warning: 
       print " we are ok" 
       sys.exit(0) 
     elif (a >= args.warning and a < args.critical): 
       print "we are warning" 
       sys.exit(1) 
     else: 
       print "Unkown" 
       sys.exit(3) 

但是问题是我的if语句的结果我从commands.getstatusoutput获取或os.popen是字符串。我如何从shell命令中获得实际的用户数量。

python test.py -c 
<type 'str'> 
value of critical is 10 
1 

result from command is 1 
<type 'str'> 
we are critical 

回答

1

将字符串转换为整数使用函数int()。例如,res_integer = int(res)

+0

确保您可能需要先手动清除空白字符串,因为空格可能会导致错误。 logins = int(str(res).strip()) –

+0

如果答案对您有帮助,请注册并标记为已接受我的答案。 –

相关问题