#!/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 " 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.