Ubuntu 20.04下如何通过编程/Shell命令指定位置配置PAM文件?
在Ubuntu 20.04中自动修改PAM配置文件的方法
方法一:使用sed命令(最直接的Shell方式)
sed是处理文本替换的常用工具,可精准定位目标行并插入内容。执行以下命令,即可在@include common-auth行后添加你的PAM模块配置:
sudo sed -i '/^@include common-auth/a #the line which i wanted to add after common auth\nauth required 2fa_test_pam.so' /etc/pam.d/sshd
命令说明:
-i:直接原地修改文件内容/^@include common-auth/:精准匹配以@include common-auth开头的行a:在匹配到的行之后追加内容- 后续字符串为要添加的注释和模块配置,用
\n分隔两行内容
方法二:使用awk命令实现
若更习惯awk,可通过以下命令完成操作:
sudo awk '/^@include common-auth/{print; print "#the line which i wanted to add after common auth"; print "auth required 2fa_test_pam.so"; next}1' /etc/pam.d/sshd > /tmp/sshd.tmp && sudo mv /tmp/sshd.tmp /etc/pam.d/sshd
命令说明:
- 匹配目标行时,先打印原行,再依次输出要添加的两行内容,
next跳过后续处理 1表示打印所有未匹配的行- 先将结果输出到临时文件再替换原文件,避免直接修改导致的文件损坏风险
方法三:Python脚本实现(适合编程场景)
如果需要集成到Python程序中,可使用以下脚本:
import tempfile import os PAM_FILE = "/etc/pam.d/sshd" INSERT_LINE = "@include common-auth" NEW_CONTENT = """#the line which i wanted to add after common auth auth required 2fa_test_pam.so""" # 读取原文件内容 with open(PAM_FILE, 'r') as f: lines = f.readlines() # 插入新内容到临时文件 with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_f: for line in lines: tmp_f.write(line) if line.strip() == INSERT_LINE: tmp_f.write(NEW_CONTENT + '\n') # 替换原文件(需root权限) os.chmod(tmp_f.name, 0o644) # 保持原文件权限一致 os.replace(tmp_f.name, PAM_FILE)
运行脚本时需加sudo,因为修改/etc/pam.d下的文件需要root权限。
注意事项
- 操作前务必备份原文件:
sudo cp /etc/pam.d/sshd /etc/pam.d/sshd.bak,避免配置错误导致无法SSH登录 - 确保
2fa_test_pam.so已安装在系统默认PAM模块路径(通常为/lib/x86_64-linux-gnu/security/),或在配置中指定完整路径 - 修改后可通过
sshd -t检查配置是否合法,避免语法错误
内容的提问来源于stack exchange,提问作者hariharan baskaran
相关产品推荐
相关产品推荐

