如何响应shell脚本中的提示符



我正在尝试回答脚本中用户的命令提示符。

命令

ufw enable

提示

Command may disrupt existing ssh connections. Proceed with operation (y|n)?

我正在使用的一段代码,但它不能正常工作:

function awk_ufw {
ufw status | grep Status | awk '{print $2}'
}
.
.
.
local CHECK_STATUS=$(awk_ufw)
if [ $CHECK_STATUS == "active" ]
then
echo "----------------------------"
echo "Firewall is already enabled!"
echo "----------------------------"
else
read -p "Before you enable the firewall, please ensure that at least inbound port for your ssh connection is open, otherwise you'll be locked out if ssh is the only way to access the system! [Please type "understood" to continue]: " UNDERSTOOD_PROMPT
if [[ $UNDERSTOOD_PROMPT == "understood" || $UNDERSTOOD_PROMPT == "UNDERSTOOD" ]]
then
ufw enable <EOF
y
EOF
if [ $? == "0" ]
then
echo "-----------------"
echo "Firewall enabled!"
echo "-----------------"
else
echo "------------------------------------------------------------------------------------------------------"
echo "Something went wrong during the process, unsure whether firewall was enabled, please recheck manually!"
echo "------------------------------------------------------------------------------------------------------"
fi
else
echo "------------------------------------------------------"
echo "Skipping the step since "Understood" wasn't entered!"
echo "------------------------------------------------------"
fi
fi

ufw enable <EOF
y
EOF
Before you enable the firewall, please ensure that at least inbound port for your ssh connection is open, otherwise you'll be locked out if ssh is the only way to access the system! [Please type "understood" to continue]: understood
./script.sh: line 84: EOF: No such file or directory
./script.sh: line 85: y: command not found
./script.sh: line 86: EOF: command not found
------------------------------------------------------------------------------------------------------
Something went wrong during the process, unsure whether firewall was enabled, please recheck manually!
------------------------------------------------------------------------------------------------------

有什么建议来纠正/改进它吗?

提前感谢!

heredocs中的结束标记不能缩进:

cat << MARKER
content
MARKER

工作,:

cat << MARKER
content
MARKER

没有。

,这里使用两个lt符号:<< MARKER< thing是重定向

在你的例子中应该是:

if [[ $UNDERSTOOD_PROMPT == "understood" || $UNDERSTOOD_PROMPT == "UNDERSTOOD" ]]
then
ufw enable <<EOF
y
EOF

但你可以考虑管道echo y |代替:

echo y | ufw enable

这在你的情况下实际上是一样的。

仅供参考awk可以进行模式匹配,因此不需要您管道grep | awk:

awk_ufw() {
ufw status | awk '/Status/ {print $2}'
}

或者只检查第一个字段:

awk_ufw() {
ufw status | awk '$1 == "Status" {print $2}'
}

快速浏览手册页可以发现您完全可以避免这个问题:

默认情况下,ufw在运行时启用防火墙时会提示在ssh。这可以通过使用'ufw——force enable'来禁用。

所以使用:

ufw --force enable
脚本中的

避免了必须传入一个按键的问题。

相关内容

  • 没有找到相关文章

最新更新