0

我正在编写一个 nagios 插件,该插件将根据登录到我的实例的用户数退出。

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
4

1 回答 1

1

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

于 2016-09-21T23:48:25.643 回答