首页 > 解决方案 > 使用 Python 替换 /etc/passwd 文件中的字符而不破坏系统

问题描述

我正在尝试强化 Ubuntu 系统并执行以下两个步骤:

  1. 运行以下命令并验证没有返回输出

grep '^+:' /etc/passwd

  1. 如果返回输出,则从 /etc/passwd 中删除任何遗留的“+”条目(如果它们存在)。

我编写了以下 python 函数:

def passwd_safe():
    file = "/etc/passwd"
    for line in fileinput.input(file,inplace=1):
        if '+' in line:
            line = line.replace('+','')
        else:
            pass

但似乎这并没有按预期工作,事实上它覆盖了整个 /etc/passwd 文件并使系统损坏。

标签: python

解决方案


您应该将该行打印到标准输出:

def passwd_safe():
    file = "/etc/passwd"
    for line in fileinput.input(file,inplace=1):
        if not line.startswith('+'):
            print(line, end='')

摘自fileinput的文档

可选的就地过滤:如果将关键字参数inplace=True传递给fileinput.input()构造FileInput函数,则将文件移动到备份文件,并将标准输出定向到输入文件(如果与备份文件同名的文件已经存在,它将被静默替换)。


推荐阅读