Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # CONFIGURATION
- CONTAINER="qbittorrent" # exact name of the torrent container in unRAID
- LISTENING_PORT="6881" # port that the torrent software is expecting to listen on for P2P connections (found in webUI settings)
- WGTUNNEL="10.2.0.1" # Local tunnel network pool (change last number to 1). Provided in VPN provider's Wireguard configuration.
- LOGFILE="/var/log/natpmp_forward.log" # where the script logs will be stored - this script will create the file if needed. /var/log directory is stored in RAM and will not persist on reboot.
- LOG_RETENTION_DAY=3 # how often (in days) the log file is purged and a new one created
- INTERVAL=45 # How often this script loops, in seconds. Some VPN providers will only reserve a port for 60 seconds.
- if ! docker exec "$CONTAINER" which natpmpc &>/dev/null; then
- echo "natpmpc not found in container '$CONTAINER'. Exiting." >&2
- exit 1
- fi
- while true; do
- mkdir -p "$(dirname "$LOGFILE")"
- # Rotate log if older than retention period
- if [[ -f "$LOGFILE" ]]; then
- FILE_AGE_DAYS=$(( ( $(date +%s) - $(stat -c %Y "$LOGFILE") ) / 86400 ))
- if (( FILE_AGE_DAYS >= LOG_RETENTION_DAY )); then
- rm -f "$LOGFILE"
- fi
- fi
- DATE_LINE="===== $(date) ====="
- echo "$DATE_LINE"
- echo "$DATE_LINE" >> "$LOGFILE"
- # Check if container is running
- if ! docker inspect -f '{{.State.Running}}' "$CONTAINER" 2>/dev/null | grep -q true; then
- echo "Container '$CONTAINER' is NOT running." | tee -a "$LOGFILE"
- sleep "$INTERVAL"
- continue
- fi
- # Run natpmpc for TCP
- TCP_OUTPUT=$(docker exec "$CONTAINER" natpmpc -a 0 "$LISTENING_PORT" tcp 1200 -g "$WGTUNNEL" 2>&1)
- echo "TCP Mapping Output:" >> "$LOGFILE"
- echo "$TCP_OUTPUT" >> "$LOGFILE"
- echo "" >> "$LOGFILE"
- # Run natpmpc for UDP
- UDP_OUTPUT=$(docker exec "$CONTAINER" natpmpc -a 0 "$LISTENING_PORT" udp 1200 -g "$WGTUNNEL" 2>&1)
- echo "UDP Mapping Output:" >> "$LOGFILE"
- echo "$UDP_OUTPUT" >> "$LOGFILE"
- echo "" >> "$LOGFILE"
- # Extract mapped port
- MAPPED_PORT=$(echo "$UDP_OUTPUT" | grep -oP 'Mapped public port \K[0-9]+' | tail -n1)
- if [[ -z "$MAPPED_PORT" || ! "$MAPPED_PORT" =~ ^[0-9]+$ ]]; then
- echo "Failed to map port or retrieve mapped port. Check natpmpc output above." | tee -a "$LOGFILE"
- echo "" >> "$LOGFILE"
- else
- echo "VPN port mapped successfully: $MAPPED_PORT to $LISTENING_PORT" | tee -a "$LOGFILE"
- echo "" >> "$LOGFILE"
- fi
- sleep "$INTERVAL"
- done
Add Comment
Please, Sign In to add comment