我正在尝试自动禁用通过 root 登录 SSH。我知道我可以手动编辑文件并这样做,但我想通过 Bash 脚本(我用来初始化我的服务器)禁用 root 登录。
我没有经常使用 sed
,但我认为它是我应该使用的,基于 this question .
在 /etc/ssh/sshd_config
中,我试图替换的行是 PermitRootLogin {any_value}
。 {any_value}
的默认值为 yes
但我希望它适用于任何值(在同一行)。
我尝试了命令 sudo sed -i "/PermitRootLogin/c\PermitRootLogin no"/etc/ssh/sshd_config
但这也替换了包含文本“PermitRootLogin”的随机评论。
所以,我不想替换以注释标记 #
开头的行。
这是我要编辑的文件的相关部分(我的注释添加了“###”):
# Authentication:
LoginGraceTime 120
PermitRootLogin yes ### I want to replace this line with "PermitRootLogin no"
StrictModes yes
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
预期的输出是:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
然后,我尝试了这个:sed -i "\(^[\# ]\)+/PermitRootLogin/c\PermitRootLogin no"/etc/ssh/sshd_config
。
这给我一个错误:sed: -e expression #1, char 48: unterminated address regex
。
我怎样才能完成我想做的事情?谢谢!
最佳答案
你可以使用这个:
sed '/^#/!s/PermitRootLogin .*/PermitRootLogin no/' /etc/ssh/sshd_config
模式 /^#/
匹配以注释开头的行。 !
否定匹配意味着后续命令将仅在非注释行上执行。
替代注释将 PermitRootLogin
替换为任何 .*
为 PermitRootLogin no
。
一旦确定它可以正常工作,请使用 -i
。
关于regex - sed 匹配并替换文件中的注释除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32159695/