add script to run command and temp open a port

This commit is contained in:
Emile Clark-Boman 2025-07-26 18:18:15 +10:00
parent 9fd929ae7b
commit 65d6c36c3e

35
scripts/openport Executable file
View file

@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Credit: u/boxofrox https://discourse.nixos.org/u/boxofrox
# Ref: https://discourse.nixos.org/t/how-to-temporarily-open-a-tcp-port-in-nixos/12306/3
USAGE="[Usage] sudo withport <port> <cmd> <args...>"
set -ueo pipefail
open-port() {
local port=$1
iptables -A INPUT -p tcp --dport $port -j ACCEPT
}
close-port() {
local port=${1:-0}
iptables -D INPUT -p tcp --dport $port -j ACCEPT
}
PORT=$1
if [[ -z "$PORT" ]]; then
echo -e "[!] Port not given\n$USAGE" >&2
exit 1
fi
shift; # Drop port argument
if [[ 0 -eq $# ]]; then
echo -e "[!] Command not given\n$USAGE" >&2
exit 1
fi
open-port $PORT
# Ensure port closes if error occurs.
trap "close-port $PORT" EXIT
# Run the command as user, not root.
runuser -u $SUDO_USER -- "$@"
# Trap will close port.