我正在编写一个shell脚本,它将在后台运行,以控制同步并管理与同步相关的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 &当从其运行的终端保持打开状态时,此脚本将按预期工作。
如果运行它的终端在同步运行时关闭,则当同步关闭时,防火墙中的端口不会关闭。
有没有办法让这个脚本正常运行--在同步关闭后关闭防火墙中的端口--当它启动的终端在同步关闭之前关闭?
这里有一个脚本,您可以用它来实验这种行为。它不需要安装同步,它输出到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 &发布于 2022-08-18 03:17:17
我使用one of triplee's suggestions来处理这个问题,为我想要运行的ufw命令启用无密码的sudo。
为此,我在/etc/sudoers.d/中创建了一个名为/etc/sudoers.d/的文件,其内容如下:
%sudo ALL=(root) NOPASSWD:/usr/sbin/ufw allow syncthing
%sudo ALL=(root) NOPASSWD:/usr/sbin/ufw delete allow syncthing然后,在没有密码的sudo的位置上,我的脚本变成:
#!/bin/bash
sync () {
sudo ufw allow syncthing
syncthing
sudo ufw delete allow syncthing
}
sync &> /dev/null &现在,即使在运行syncthing时关闭了从其运行的终端,当syncthing关闭时,ufw delete命令仍然会触发。
发布于 2022-07-24 07:13:52
我猜您用sudo创建的sudo -v缓存与终端会话绑定在一起,并在注销时立即消失。
简单的解决方法是使用sudo运行整个命令。
#!/bin/sh
sync () {
ufw allow syncthing
su "$SUDO_USER" -c syncthing
ufw delete allow syncthing
}
test "$SUDO_USER" && test -w / || {
echo "${0##*/}: run this script using sudo" >&2
exit 126
}
sync >/dev/null 2>&1 &我还重构了对调用方的重定向;希望这样可以更容易地将其更改为将诊断信息从ufw和syncthing写入日志文件。
su命令以调用用户的身份运行syncthing;我不熟悉它的功能,因此如果它需要登录会话或对桌面环境的访问,例如显示GUI (如果您不介意将它作为root运行),这可能是不够的。
只有重定向使用了Bash语法,所以用可移植的sh语法代替这些语法,我就可以将shebang更改为#!/bin/sh;在许多系统上,这应该允许这个脚本消耗更少的资源。
或者,更新您的sudoers特权,以允许您以密码方式运行这些特定的ufw命令。如果您有/etc/sudoers.d,您可以在那里创建一个新文件来授予自己这些权限。
you ALL=(root) NOPASSWD: /usr/bin/ufw allow syncthing
you ALL=(root) NOPASSWD: /usr/bin/ufw delete allow syncthing(很明显,您将用实际帐户名替换you,并可能检查ufw的路径,我只是猜到了这一点)。
https://stackoverflow.com/questions/73096397
复制相似问题