从python脚本中解析出特定参数

从python脚本中解析出特定参数

我有一个名为“accounts”的 chage 输出,我自己对其进行了格式化。它基本上将用户的名称列为一个部分,然后是其下方的信息(即参数)。我基本上想解析出所有具有“Account expires = never”的帐户,并将该部分名称提供给新文件。以下是“accounts”文件的样子:

[user1]
Last_password_change = password_must_be_changed
Password_expires = never
Password_inactive = never
Account_expires = never
Minimum_number_of_days_between_password_change = 7
Maximum_number_of_days_between_password_change = 90
Number_of_days_of_warning_before_password_expires = 14

[user2]
Last_password_change = password_must_be_changed
Password_expires = never
Password_inactive = never
Account_expires = never
Minimum_number_of_days_between_password_change = 7
Maximum_number_of_days_between_password_change = 90
Number_of_days_of_warning_before_password_expires = 14

这是我目前所拥有的,但似乎无法完全按照我想要的方式获得它。

#!/usr/bin/python

from ConfigParser import RawConfigParser
import re
import sys

# Read configuration from ~/accounts
_cfg = RawConfigParser()
_cfg.read('accounts')
cfg = dict()
for sect in _cfg.sections():
        cfg[sect] = dict()
        for (name, value) in _cfg.items(sect):
                cfg[sect][name] = value

                if cfg[sect]['Account_expires'] == "never":

                        f = open('access','w')
                        f.write('still has access')
                        f.close()

我意识到我只在名为“access”的新文件中输入了“仍然具有访问权限”,但我真的很想在那里输出用户名。感谢您的帮助。

答案1

您的代码不必要地将内容复制到另一个数组。这被简化为对结果进行简单循环_cfg。我不是在写access,而是暗示如何收集所有信息,然后在主循环之后最后将其全部写出。(如果您有大量数据,那么边读边写又开始有意义了,但对于简单、快速的工作,我会先收集,然后写。)

#!/usr/bin/env python

from ConfigParser import RawConfigParser


# Read configuration from ~/accounts
_cfg = RawConfigParser()
_cfg.read('accounts')

users = []
for sect in _cfg.sections():
    for (name, value) in _cfg.items(sect):
        # Notice that the names are normalized to all lowercase
        if name in ['account_expires', 'password_inactive'] and value=="never":
            users.append(sect)
            break  # done with this user, break out of inner loop
for user in users:
    print("User %s still has access" % user)

您从来没有使用过,并且您的脚本中还存在一些其他死代码resys

答案2

这是我注意到的真正有效的方法。我将 len(never) == 1 更改为 len(never) == 2。它似乎有效,我认为这是因为它正在寻找这两个选项(帐户过期和密码不活动字段)的 2 个匹配项的确切长度。我说得对吗?

users = []
for sect in _cfg.sections():
    never = []
    for (name, value) in _cfg.items(sect):
        print("# %s: %s = %s" % (sect, name, value))
        # Notice that the names are normalized to all lowercase
        if name in ['account_expires', 'password_inactive'] and value=="never":
            never.append(name)
    # Slightly ugly, check for exactly one value in "never"
    if len(never) == 2:
        users.append(sect)
for user in users:
    print("User %s still has access" % user)

相关内容