1. #!/bin/bash
  2.  
  3. #### CLEAN UP ####
  4.  
  5. # Flush old redirect rules
  6. sudo iptables -t nat -D OUTPUT -o lo --dst 127.0.0.1 -p tcp --dport 5939 -j TEAMVIEWER
  7. sudo iptables -t nat -F TEAMVIEWER
  8. sudo iptables -t nat -X TEAMVIEWER
  9.  
  10. # Kill old teamviewerd
  11. killall teamviewerd
  12.  
  13.  
  14.  
  15. #### START ####
  16.  
  17. # Create the first part of a new redirect rule
  18. sudo iptables -t nat -N TEAMVIEWER
  19. sudo iptables -t nat -A OUTPUT -o lo --dst 127.0.0.1 -p tcp --dport 5939 -j TEAMVIEWER
  20.  
  21. # Create pid-file and launch teamviewerd
  22. sudo touch /var/run/teamviewerd.pid
  23. sudo chown $USER /var/run/teamviewerd.pid
  24. /opt/teamviewer8/tv_bin/teamviewerd
  25.  
  26. # Find out what port is opened by teamviewerd
  27. while [[ -z $port ]]; do
  28.     pid=$(cat /var/run/teamviewerd.pid)
  29.     [[ -n $pid ]] && port=$(lsof -an -iTCP -sTCP:LISTEN -p $pid -Fn | grep '^n' | sed -r 's/^n.*:([[:digit:]]+)$/\1/')
  30.     sleep 0.1
  31. done
  32.  
  33. # Create the second part of a new redirect rule
  34. sudo iptables -t nat -A TEAMVIEWER -p tcp -j REDIRECT --to-ports $port
  35.  
  36. # Launch teamviewer
  37. teamviewer
  38.  
  39.  
  40.  
  41. #### STOP AND CLEAN UP ####
  42.  
  43. # Kill teamviewerd
  44. killall teamviewerd
  45.  
  46. # Flush redirect rules
  47. sudo iptables -t nat -D OUTPUT -o lo --dst 127.0.0.1 -p tcp --dport 5939 -j TEAMVIEWER
  48. sudo iptables -t nat -F TEAMVIEWER
  49. sudo iptables -t nat -X TEAMVIEWER