- You can just run multiple commands sequentially in
ExecStart by running the commands in a shell:
ExecStart=sh -c '/usr/bin/socat tcp-listen:1111,reuseaddr,fork tcp:localhost:5555; /usr/bin/socat tcp-listen:2222,reuseaddr,fork tcp:localhost:6666;/usr/bin/socat tcp-listen:3333,reuseaddr tcp:localhost:7777'
- You can just put these multiple commands in a shell script, add the shebang line to it, mark it executable, and put it in
/usr/bin/mysocatscript.sh, then use that script in ExecStart:
ExecStart=/usr/bin/mysocatscript.sh
This is already better than 1., as you can then write your script to abort when one of these things fail, or be more informative.
- You write a template unit file, i.e., a unit file that ends in
@.service, let's call it /usr/lib/systemd/systenm/[email protected]. You can then pass a parameter %i:
[Unit] Description="socat single forwarding" [Service] Type=simple Restart=on-failure RestartSec=10 ExecStart=/bin/bash -c "inport=$(echo %i | cut -d: -f1); outport=$(echo %i | cut -d: -f2); /usr/bin/socat tcp-listen:${inport},reuseaddr tcp:localhost:${outport}"
Now, you can set up a socat forwarding simply by starting socat-forward@port_in:port_out, e.g. systemctl start socat-forward@1111:5555.
You can then just write a unit file socat-connections.service:
[Unit] Description="socat custom forwardings" [Service] Type=simple Restart=on-failure RestartSec=60 Requires=socat-forward@1111:5555 socat-forward@2222:6666 socat-forward@3333:7777 [Install] WantedBy=multi-user.target
Clearly, 3. is the "best" option:
- You actually get a reusable, configurable service.
- You can pull up and down individual forwardings as needed.
- When one of your 3 socat calls fails, only that is restarted, or reported as failing, etc. So,
systemctl status will actually tell you which forwarding did not work! - You can set up and take down your set of forwardings through a single service, and
- you can actually make the thing that depends on your forwardings (for example, your development web server, your SSH server, …) depend on the port forwardings, so that only the forwardings needed are set up.
Remarks
- Probably an indication of you not actually needing a system, but a user service, if the user runnning the program is
ubuntu, and not nobody, or a daemon user - Should quite possibly depend on networking being established before
- Is this really a use case for
socat? Looks to me as if masquerading / NAT would do the same for you, but at lower CPU usage.