python - 使用 Python 替换 /etc/passwd 文件中的字符而不破坏系统
问题描述
我正在尝试强化 Ubuntu 系统并执行以下两个步骤:
- 运行以下命令并验证没有返回输出
grep '^+:' /etc/passwd
- 如果返回输出,则从 /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 文件并使系统损坏。
解决方案
您应该将该行打印到标准输出:
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
函数,则将文件移动到备份文件,并将标准输出定向到输入文件(如果与备份文件同名的文件已经存在,它将被静默替换)。
推荐阅读
- azure - 在我的工作区中获取仪表板时,Power BI API 返回 403 被禁止
- jquery - 如何将无序列表的最后一个元素输出到控制台?
- php - 此路由不支持 GET 方法。支持的方法:PUT。拉拉维尔 8
- javascript - parentNode.removeChild() 实际上是如何工作的?
- c# - 使用 C# 检测文本中的电子邮件和社交媒体帐户
- c# - 返回函数中的 C# await 语句
- java - JavaFX Line 没有按原样移动
- javascript - 在 Modal 中集中 iframe 并删除滚动条
- java - 尝试使用类对象作为方法的参数时出现“变量可能未初始化”的错误,尝试使用 IF 来避免该问题(JAVA)
- javascript - 变量声明是一个语句,但为什么函数表达式不是?