Python "fileinput"模块在 PAM 文件中创建重复条目



我有以下四个PAM规则

auth required pam_faillock.so preauth audit silent deny=5 unlock_time=0
auth [success=1 default=bad] pam_unix.so
auth [default=die] pam_faillock.so authfail audit deny=5 unlock_time=0
auth sufficient pam_faillock.so authsucc audit deny=5 unlock_time=0`

要添加到/etc/pam.d/system-auth-ac/etc/pam.d/password-auth-acPAM文件,但有以下条件:

1( 如果PAM条目已经可用,但是具有不同的denyunlock_time值,则其必须相应地用值deny=5unlock_time=0重置;

2( 如果PAM规则在整个文件中根本不可用,则应将该条目插入文件中第一个/起始auth规则条目的上方。

我尝试了以下代码:

files = [
"/etc/pam.d/system-auth-ac",
"/etc/pam.d/password-auth-ac"
]
rules = [
"auth sufficient pam_faillock.so authsucc audit deny=5 unlock_time=0",
"auth [default=die] pam_faillock.so authfail audit deny=5 unlock_time=0",
"auth [success=1 default=bad] pam_unix.so",
"auth required pam_faillock.so preauth audit silent deny=5 unlock_time=0"
]
for file in files:
for rule in rules:
flag = 0
regexrule = re.sub(r'([[]])', r'\1', rule)
grepRule = re.sub(r'deny=5', 'deny=.*', regexrule)
params = subprocess.Popen("egrep '%s' %s"%(regexrule, file), stdout=subprocess.PIPE, shell=True).communicate()[0].split("n")
if len(params) == 1:
for pamd in fileinput.FileInput(file, 'inplace=1'):
if re.match(r'auths+requireds+pam_tally2.so', pamd):
continue
if re.match(grepRule, pamd) and not flag:
pamd = rule
flag = 1
elif pamd.startswith("auth") and not flag:
pamd = rule + "n" + pamd
flag = 1
print pamd.strip()

当任何参数值与我指定的值不同时,它会插入重复的PAM条目(而不是替换这些值(。

此外,上面的代码一团糟,我想得到一个优雅的解决方案。

使用以下方法解决:

方法1:

for file in files:
for rule in rules:
flag = 0
regexrule= re.sub(r'([[]])',r'\1',rule)
grepRule = re.sub(r'unlock_time=[0-9]*', 'unlock_time=.*',regexrule)
grepRule = re.sub(r'deny=[0-9]*', 'deny=.*', grepRule)
params = subprocess.Popen("egrep '%s' %s"%(grepRule,file),stdout=subprocess.PIPE,shell=True).communicate()[0].split("n")
if len(params) == 1:
for pamd in fileinput.FileInput(file,'inplace=1'):
if re.match(r'auths+requireds+pam_tally2.so',pamd):
continue
if re.match(grepRule,pamd) and not flag:
pamd = rule
flag = 1
elif pamd.startswith("auth") and not flag:
pamd = rule + "n" + pamd
flag = 1
print pamd.strip()
elif len(params) == 2:
for pamd in fileinput.FileInput(file,'inplace=1'):
if re.match(grepRule,pamd) and not flag:
pamd =  rule
print pamd.strip()

方法2:

for rule in rules:
flag = 0
grepRule = re.sub(r'([[]])',r'\1', rule)
grepRule = re.sub(r'deny=d+', 'deny=.*', grepRule)
grepRule = re.sub(r'unlock_time=d+', 'unlock_time=.*', grepRule)
for pamd in fileinput.FileInput(files=("/etc/pam.d/system-auth-ac"), inplace=1):
if re.match(grepRule, pamd.strip()):
flag = 1
sys.stdout.write(re.sub(grepRule, rule, pamd))
else:
if not flag:
for pamd in fileinput.FileInput(files=("/etc/pam.d/system-auth-ac"), inplace=1):
if pamd.startswith("auth") and not flag:
pamd = rule + "n" + pamd
flag = 1
print pamd.strip()

但是,如果在文件中找不到指定的规则,则第二种方法仅适用于一个文件。对于以上代码的任何改进点,我们都非常欢迎。

最新更新