大网数据广告活动
服务器运维问答

Systemd: How to run script before service starts, after service starts and after service stops

· 52CE 我爱测

I have a daemon.service that starts every time on different port so I need to allow this random port through iptables every time it starts and deny it every time it stops. So I need to run a script that allows every port in iptab…

问题原文

原帖链接 · FieryRider · CC BY-SA 3.0

I have a daemon.service that starts every time on different port so I need to allow this random port through iptables every time it starts and deny it every time it stops. So I need to run a script that allows every port in iptables before the daemon.service starts then run script that changes 'allow every port' rule to 'allow only the port that daemon.service uses' after the daemon.service starts and when daemon.service stops I need to run a script that removes that rule. NOTE that daemon.service runs as it's own user and to allow/deny ports through iptables i need to do it as root so I can't use ExecStartBefore/ExecStartAfter in daemon.service

Here is a scheme (kinda) of what needs to happen:

systemctl start deamon.service
|-executing as root 'iptables -A OUTPUT -p tcp -m multiport --dports 0:65535 -j ACCEPT'
|-starting daemon.service as it's own user (not as root)
|-finding (as root) what ports daemon.service uses with netstat (I can do that so I don't need explanation on how to do it)
|-executing as root 'iptables -D OUTPUT -p tcp -m multiport --dports 0:65535 -j ACCEPT'
|-executing as root 'iptables -A OUTPUT -p tcp -m multiport --dports 56731,31267 -j ACCEPT' (ports that were found by netstat)
systemctl stop daemon.service
|-stopping daemon.service as it's own user (not as root)
|-executing as root 'iptables -D OUTPUT -p tcp -m multiport --dports 56731,31267 -j ACCEPT'

NOTE: daemon.service can't be made to run as specified port (not random)

I'm running debian btw.

已采纳解答

原帖链接 · Thomas · CC BY-SA 3.0

Well, for setting the iptables stuff you would have to add the service user to the sudoers and run those commands with sudo ....
Nevertheless, instead of fiddling around with iptables, you could open a static port in your firewall, then connect that static port to your dynamic daemon port with socat.

socat -s TCP4-LISTEN:<open-firewall-port>,fork TCP4:localhost:<random-daemon-port>

Then you only would have to run the ExecStartAfter script which determines the random port and starts socat to connect those ports.

Please also note that you might have to change TCP4-LISTEN, TCP4 and/or localhost to match your configuration.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-04-21)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。