Reputation: 293
I am trying to run a subprocess with my own iptables rule for a subprocess using subprocess.open. The command works with shell=True
. But when I remove the shell option, which it sets the shell option to false. The command doesn't work anymore.
Here is the working code:
HOST = localhost
PORT: 8000
group_name = "no-external-internet"
subprocess.Popen(
f"addgroup --system {group_name}; "
f"iptables -A OUTPUT -m owner --gid-owner {group_name} -d {HOST} -p tcp --sport {PORT} -j ACCEPT; "
f"iptables -A OUTPUT -m owner --gid-owner {group_name} -j REJECT; "
f"ip6tables -A OUTPUT -m owner --gid-owner {group_name} -j REJECT; "
f"sg {group_name} './run.sh {HOST}:{PORT}'",
shell=True,
cwd="some directory",
preexec_fn=os.setsid,
)
When I remove the shell=True
and used the shlex to split my command:
subprocess.Popen(
shlex.split(
f"addgroup --system {group_name}; "
f"iptables -A OUTPUT -m owner --gid-owner {group_name} -d {HOST} -p tcp --sport {PORT} -j ACCEPT; "
f"iptables -A OUTPUT -m owner --gid-owner {group_name} -j REJECT; "
f"ip6tables -A OUTPUT -m owner --gid-owner {group_name} -j REJECT; "
f"sg {group_name} './run.sh {HOST}:{PORT}'",
),
cwd="some directory",
preexec_fn=os.setsid,
)
I got errors:
Unknown option: m
Unknown option: gid-owner
Option d is ambiguous (debug, disabled-login, disabled-password)
Unknown option: p
Unknown option: sport
Unknown option: j
Unknown option: m
Unknown option: gid-owner
Unknown option: j
Unknown option: m
Unknown option: gid-owner
Unknown option: j
I print the split result and it looks okay:
['addgroup', '--system', 'no-external-internet;', 'iptables', '-A', 'OUTPUT', '-m', 'owner', '--gid-owner', 'no-external-internet', '-d', '127.0.0.1', '-p', 'tcp', '--sport', '8000', '-j', 'ACCEPT;', 'iptables', '-A', 'OUTPUT', '-m', 'owner', '--gid-owner', 'no-external-internet', '-j', 'REJECT;', 'ip6tables', '-A', 'OUTPUT', '-m', 'owner', '--gid-owner', 'no-external-internet', '-j', 'REJECT;', 'sg', 'no-external-internet', './run.sh 127.0.0.1:8000']
Why this doesn't work and how could I solve it
Upvotes: 3
Views: 489