【发布时间】:2022-08-18 11:17:17
【问题描述】:
我正在编写一个 shell 脚本,它将在后台运行以控制 Syncthing 并管理与 Syncthing 相关的 UFW 防火墙。
这里是简化的形式:
#!/bin/bash
sync () {
# Open the ports which Syncthing communicates on.
sudo ufw allow syncthing &> /dev/null
# Start Syncthing, and block script execution here until Syncthing is closed.
syncthing &> /dev/null
# Close the ports which Syncthing communicates on once it is closed.
sudo ufw delete allow syncthing &> /dev/null
}
# Get sudo before the sync function is backgrounded.
sudo -v
# Run the sync function in the background.
sync &
当运行它的终端保持打开状态时,此脚本将按预期工作。
如果运行它的终端在 Syncthing 运行时关闭,则防火墙中的端口不会在 Syncthing 关闭时关闭。
有没有办法让这个脚本正常运行——在 Syncthing 关闭后关闭防火墙中的端口——当它启动的终端在 Syncthing 关闭之前关闭?
这是一个脚本,您可以使用它来试验这种行为。它不需要安装 Syncthing,它会输出到syslog:
#!/bin/bash
test_function () {
echo \'-- Opening port\' | logger -t TEST
sudo ufw allow 80 | logger -t TEST
echo \'-- Close the terminal you started this script from in the next 10 seconds\' | logger -t TEST
sleep 10
echo \'-- Closing port\' | logger -t TEST
sudo ufw delete allow 80 | logger -t TEST
}
sudo -v
test_function &