【问题标题】:SSHD Config checking in bash scriptSSHD 配置检查 bash 脚本
【发布时间】:2018-01-15 17:14:28
【问题描述】:

我目前正在制作一个简单的安全审计脚本,它会针对配置中的每个不匹配情况打印 OK/Error。 场景是下一个 - 例如,对于 SSHD_Config,如果 case:

if [ "`grep -E ^Protocol /etc/ssh/sshd_config`" == "Protocol 1" ]; then
  echo "Protocol should be set to 2";
fi

问题是——如果某个变量和它的值之间有多个空格怎么办? (例如协议 2 或 PermitRootLogin No); /*s/s 和类似的技巧没有帮助。

有没有人有在 bash 脚本中检查 SSHD 配置的示例来在这里发布案例? 提前致谢!

【问题讨论】:

    标签: bash security ssh redhat openssh


    【解决方案1】:

    grep 的-E 选项将其置于扩展正则表达式模式。因此,您可以使用扩展正则表达式(^Protocol +1 表示以Protocol 开头的行,后跟1 个或多个空格,然后是字符1):

    if grep -Eq '^Protocol +1' /etc/ssh/sshd_config; then
      echo "Protocol should be set to 2";
    fi
    

    [yY] 表示字符yY

    if grep -Eq '^PermitEmptyPasswords +[yY][eE][sS]' /etc/ssh/sshd_config; then
      echo "PermitEmptyPasswords should be set to no";
    elif grep -Eq '^PermitEmptyPasswords +[nN][oO]' /etc/ssh/sshd_config; then
      echo "PermitEmptyPasswords meets requirements";
    fi
    

    还有许多其他有趣的功能。备注:

    • 您可能应该考虑在sshd_config 文件中有多个匹配行的情况。
    • -q grep 选项禁止打印匹配行。如果找到匹配的行,grep 只会以状态 0 退出,否则状态为 1(未找到)或 2(错误)。
    • if 语句可以直接跟在要执行的命令列表之后。如果列表的退出状态为 0,则采用 then 分支。在我们的例子中,列表只是grep

    【讨论】:

    • 那么如何设置是和否的大小写(例如 PermitEmptyPasswords)?例如:如果 grep -Eq '^PermitEmptyPasswords +yes' /etc/ssh/sshd_config;然后回显“值不符合要求”; else echo "Value does meet requirements"
    • @Kristian 将此添加到我的答案中。试着找一个关于扩展正则表达式的文档,这是一个非常有用的知识。
    • 感谢您的提示,我是脚本新手,所以现在有些程序还不清楚 1/1。
    • 对不起,可能是垃圾邮件,它适用于变量/值之间的空格,但是如果该行以空格开头然后是单词 Protocol 例如?
    • ^ *Protocol +1 但实际上,看看正则表达式,我坚持认为这是要知道的。
    【解决方案2】:


    试试这个:

    if [[ $(cat /etc/ssh/sshd_config | awk '/^Protocol/{print $2}') != 2 ]]; then 
        echo "Protocol should be set to 2"
    fi
    

    【讨论】:

      【解决方案3】:

      使用 grep 获取协议 2 行。

      然后删除可能包含 2 的协议 1 行,例如协议 2,1

      最后应该排除哈希。最后回显需要的字符串。

      在 grep 中添加 -i 以不区分大小写

      grep -i "Protocol 2" /etc/ssh/sshd_config | grep -v "#"|grep -v "Protocol 1"|| echo "Protocol 2 is needed"
      

      【讨论】:

        猜你喜欢
        • 2022-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多