#!/bin/bash
#### CLEAN UP ####
# Flush old redirect rules
sudo iptables -t nat -D OUTPUT -o lo --dst 127.0.0.1 -p tcp --dport 5939 -j TEAMVIEWER
sudo iptables -t nat -F TEAMVIEWER
sudo iptables -t nat -X TEAMVIEWER
# Kill old teamviewerd
killall teamviewerd
#### START ####
# Create the first part of a new redirect rule
sudo iptables -t nat -N TEAMVIEWER
sudo iptables -t nat -A OUTPUT -o lo --dst 127.0.0.1 -p tcp --dport 5939 -j TEAMVIEWER
# Create pid-file and launch teamviewerd
sudo touch /var/run/teamviewerd.pid
sudo chown $USER /var/run/teamviewerd.pid
/opt/teamviewer8/tv_bin/teamviewerd
# Find out what port is opened by teamviewerd
while [[ -z $port ]]; do
pid=$(cat /var/run/teamviewerd.pid)
[[ -n $pid ]] && port=$(lsof -an -iTCP -sTCP:LISTEN -p $pid -Fn | grep '^n' | sed -r 's/^n.*:([[:digit:]]+)$/\1/')
sleep 0.1
done
# Create the second part of a new redirect rule
sudo iptables -t nat -A TEAMVIEWER -p tcp -j REDIRECT --to-ports $port
# Launch teamviewer
teamviewer
#### STOP AND CLEAN UP ####
# Kill teamviewerd
killall teamviewerd
# Flush redirect rules
sudo iptables -t nat -D OUTPUT -o lo --dst 127.0.0.1 -p tcp --dport 5939 -j TEAMVIEWER
sudo iptables -t nat -F TEAMVIEWER
sudo iptables -t nat -X TEAMVIEWER