使用Python获取Linux系统的各种信息

2019-10-06 12:02:44丽君

                uid_min = int(line.split()[1].strip())
           
            if line.startswith('UID_MAX'):
                uid_max = int(line.split()[1].strip())

    return uid_min, uid_max

# Get the users from /etc/passwd
def getusers(no_system=False):

    uid_min, uid_max = read_login_defs()

    if uid_min is None:
        uid_min = 1000
    if uid_max is None:
        uid_max = 60000

    users = pwd.getpwall()
    for user in users:
        if no_system:
            if user.pw_uid >= uid_min and user.pw_uid <= uid_max:
                print('{0}:{1}'.format(user.pw_name, user.pw_shell))
        else:
            print('{0}:{1}'.format(user.pw_name, user.pw_shell))

if __name__=='__main__':

    parser = argparse.ArgumentParser(description='User/Password Utility')

    parser.add_argument('--no-system', action='store_true',dest='no_system',
                        default = False, help='Specify to omit system users')

    args = parser.parse_args()
    getusers(args.no_system)

使用--help选项执行上面的程序,你会看到友好的帮助信息:可选项以及它们的作用。


$ ./getusers.py --help
usage: getusers.py [-h] [--no-system]

User/Password Utility

optional arguments:
  -h, --help   show this help message and exit
  --no-system  Specify to omit system users

上面程序使用的一个例子,如下所示:


$ ./getusers.py --no-system
gene:/bin/bash

当你传入一个非法的参数,这个程序就会发牢骚(报错)

$ ./getusers.py --param
usage: getusers.py [-h] [--no-system]
getusers.py: error: unrecognized arguments: --param

在上面的程序中,我们简单的理解了如何使用argparse模块。parser = argparse.ArgumentParser(description="User/Password Utility")语句创建了一个带说明程序是做什么的可选描述的ArgumentParser对象,
然后,我们添加参数。我们想要程序能够识别接下来这条语句 add_argument()。