Script to change transmission listening port

Ask for help and report issues with the GTK+ version of Transmission
plainzwalker
Posts: 6
Joined: Thu Sep 10, 2015 12:28 am

Script to change transmission listening port

Postby plainzwalker » Thu Sep 10, 2015 12:31 am

I am trying to run a script that will automatically change the port that transmission is listening on. My network setup is more advanced than the typical person I guess and this is the only way to get it to work since the port changes whenever my VPN decides to release a new port. I already have a sample script, but it is intended for a Synology system and when I try it on my ubuntu server it gives an error
transmission-port: 40: transmission-port: Syntax error: end of file unexpected (expecting "then")


Can any one help me please?

Thank you

Original Synology Script:

Code: Select all

#!/bin/sh
export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/syno/sbin:/usr/syno/bin:/usr/local/sbin:/usr/local/bin

# Script to update port used by Transmission torrent client
# Developed for use on Synology DSM. Should work on other platforms.
# v1.0 (22nd January 2014)
# Written by Andy Fox

# This script is configured to work with Transmission that has password
# protection on the web GUI. You can remove this stuff if you don't use it.
USERNAME="username"
PASSWORD="password"

if [ ! -e /tmp/pia_port.txt ]; then

   logger -p user.crit "transmission-port: Setting up port forward for first time."
   cd /tmp && curl -O -k https://192.168.1.1/pia_port.txt
   /usr/local/transmission/bin/transmission-remote --auth $USERNAME:$PASSWORD -p $(cat /tmp/pia_port.txt)
   
else

   CURPORT=`cat /tmp/pia_port.txt`
   cd /tmp && curl -o pia_new.txt -k https://192.168.1.1/pia_port.txt
   NEWPORT=`cat /tmp/pia_new.txt`

   logger -p user.crit "transmission-port: Current port: $CURPORT"
   logger -p user.crit "transmission-port: New Port: $NEWPORT"
   
   if [ "$CURPORT" = "$NEWPORT" ]; then
      logger -p user.crit "transmission-port: Port not changed. Exiting."
      exit 0
   fi
   
   logger -p user.crit "transmission-port: Updating port."
   mv /tmp/pia_new.txt /tmp/pia_port.txt
   /usr/local/transmission/bin/transmission-remote --auth $USERNAME:$PASSWORD -p $(cat /tmp/pia_port.txt)
   
fi


x190
Posts: 5094
Joined: Sun Nov 30, 2008 4:59 am

Re: Script to change transmission listening port

Postby x190 » Thu Sep 10, 2015 1:56 am

Code: Select all

if [ "$CURPORT" = "$NEWPORT" ]; then
      logger -p user.crit "transmission-port: Port not changed. Exiting."
      exit 0
   fi

Maybe change 'fi' to 'else'? Then add another 'fi' at the end.

Code: Select all

   if [ "$CURPORT" = "$NEWPORT" ]; then
      logger -p user.crit "transmission-port: Port not changed. Exiting."
      exit 0
   
   else
      logger -p user.crit "transmission-port: Updating port."
      mv /tmp/pia_new.txt /tmp/pia_port.txt
      /usr/local/transmission/bin/transmission-remote --auth $USERNAME:$PASSWORD -p $(cat /tmp/pia_port.txt)

   fi
fi
The stone age didn’t end because we ran out of stones.
---The Great Disruption - by Paul Gilding
https://paulgilding.com/
-------------------------------------------------

plainzwalker
Posts: 6
Joined: Thu Sep 10, 2015 12:28 am

Re: Script to change transmission listening port

Postby plainzwalker » Thu Sep 10, 2015 2:17 am

No luck, it has to do with something with how the script is closed out I believe, something with how this section is closed out.

Code: Select all

   else
   
   logger -p user.crit "transmission-port: Updating port."
   mv /tmp/pia_new.txt /tmp/pia_port.txt
   /usr/bin/transmission-remote --auth $USERNAME:$PASSWORD -p $(cat /tmp/pia_port.txt)


No matter how I close it I still get the same error

plainzwalker
Posts: 6
Joined: Thu Sep 10, 2015 12:28 am

Re: Script to change transmission listening port

Postby plainzwalker » Thu Sep 10, 2015 3:28 am

Okay, finally got it to work. Now they issue is itsn't actually changing the settings.json file. I have manually tried to pass the transmission-remote -p command but I get an unauthorized error, even after disabling everything in rpc. Getting ready to give up I think. Any suggestions?

Code: Select all

#!/bin/sh
export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/syno/sbin:/usr/syno/bin:/usr/local/sbin:/usr/local$

# Script to update port used by Transmission torrent client
# Developed for use on Synology DSM. Should work on other platforms.
# v1.0 (22nd January 2014)
# Written by Andy Fox

# This script is configured to work with Transmission that has password
# protection on the web GUI. You can remove this stuff if you don't use it.
#USERNAME=""
#PASSWORD=""

if [ ! -e /tmp/pia_port.txt ]; then

        logger -p user.crit "transmission-port: Setting up port forward for first time."
        cd /tmp && curl -O -k https://192.168.1.1/pia_port.txt
        /usr/bin/transmission-remote --auth $USERNAME:$PASSWORD -p $(cat /tmp/pia_port.txt)

else

        CURPORT=`cat /tmp/pia_port.txt`
        cd /tmp && curl -o pia_new.txt -k https://192.168.1.1/pia_port.txt
        NEWPORT=`cat /tmp/pia_new.txt`

        logger -p user.crit "transmission-port: Current port: $CURPORT"
        logger -p user.crit "transmission-port: New Port: $NEWPORT"

        if [ "$CURPORT" = "$NEWPORT" ]; then
                logger -p user.crit "transmission-port: Port not changed. Exiting."
                exit 0
        fi

        logger -p user.crit "transmission-port: Updating port."
        mv /tmp/pia_new.txt /tmp/pia_port.txt
        /usr/bin/transmission-remote --auth $USERNAME:$PASSWORD -p $(cat /tmp/pia_port.txt)

fi


x190
Posts: 5094
Joined: Sun Nov 30, 2008 4:59 am

Re: Script to change transmission listening port

Postby x190 » Thu Sep 10, 2015 5:44 am

If you don't want to use '--auth $USERNAME:$PASSWORD', then remove it from the script.

If you have access to the settings.json file, edit it directly or if you use the Web Interface, you can change the port there, I think.

https://trac.transmissionbt.com/wiki/Ed ... s#PeerPort
Last edited by x190 on Thu Sep 10, 2015 3:04 pm, edited 1 time in total.
The stone age didn’t end because we ran out of stones.
---The Great Disruption - by Paul Gilding
https://paulgilding.com/
-------------------------------------------------

plainzwalker
Posts: 6
Joined: Thu Sep 10, 2015 12:28 am

Re: Script to change transmission listening port

Postby plainzwalker » Thu Sep 10, 2015 8:36 am

I removed that, and even turned off authentication in the settings.json. I would make the changes manually but I do not know how often my VPN (PIA) changes the port that is forwarded. Also I noticed that even after changing the settings.json in both locations and within transmission itself it still seemed to use the old port. It wasn't until changing it at all 3 spots and then restarting transmission-daemon did it actually take the port.

Here is the error I get

Code: Select all

jeff@behemuth:/usr/local/bin$ sudo ./transmission-port
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100     6  100     6    0     0     91      0 --:--:-- --:--:-- --:--:--    92
Unexpected response: <h1>401: Unauthorized</h1>Unauthorized User-www-form-urlencoded


And here is my settings.json

Code: Select all

jeff@behemuth:/usr/local/bin$ sudo cat /etc/transmission-daemon/settings.json
{
    "alt-speed-down": 1500,
    "alt-speed-enabled": false,
    "alt-speed-time-begin": 360,
    "alt-speed-time-day": 127,
    "alt-speed-time-enabled": true,
    "alt-speed-time-end": 1380,
    "alt-speed-up": 1000,
    "bind-address-ipv4": "0.0.0.0",
    "bind-address-ipv6": "::",
    "blocklist-enabled": true,
    "blocklist-url": "http://list.iblocklist.com/?list=gyisgnzbhppbvsphucsw&fileformat=p2p&archiveformat=gz",
    "cache-size-mb": 4,
    "dht-enabled": true,
    "download-dir": "/media/Media/shares/Downloads",
    "download-limit": 100,
    "download-limit-enabled": 0,
    "download-queue-enabled": true,
    "download-queue-size": 5,
    "encryption": 0,
    "idle-seeding-limit": 60,
    "idle-seeding-limit-enabled": false,
    "incomplete-dir": "/media/Media/downloads/incomplete",
    "incomplete-dir-enabled": false,
    "lpd-enabled": true,
    "max-peers-global": 200,
    "message-level": 2,
    "peer-congestion-algorithm": "",
    "peer-id-ttl-hours": 6,
    "peer-limit-global": 600,
    "peer-limit-per-torrent": 100,
    "peer-port": 40696 ,
    "peer-port-random-high": 65535,
    "peer-port-random-low": 29152,
    "peer-port-random-on-start": false,
    "peer-socket-tos": "default",
    "pex-enabled": true,
    "port-forwarding-enabled": true,
    "preallocation": 1,
    "prefetch-enabled": 1,
    "queue-stalled-enabled": true,
    "queue-stalled-minutes": 30,
    "ratio-limit": 4,
    "ratio-limit-enabled": true,
    "rename-partial-files": true,
    "rpc-authentication-required": false,
    "rpc-bind-address": "0.0.0.0",
    "rpc-enabled": false,
    "rpc-password": "",
    "rpc-port": 9091,
    "rpc-url": "/transmission/",
    "rpc-username": "",
    "rpc-whitelist": "*.*.*.*",
    "rpc-whitelist-enabled": false,
    "scrape-paused-torrents-enabled": true,
    "script-torrent-done-enabled": false,
    "script-torrent-done-filename": "",
    "seed-queue-enabled": false,
    "seed-queue-size": 10,
    "speed-limit-down": 100,
    "speed-limit-down-enabled": false,
    "speed-limit-up": 3,
    "speed-limit-up-enabled": false,
    "start-added-torrents": true,
    "trash-original-torrent-files": false,
    "umask": 2,
    "upload-limit": 100,
    "upload-limit-enabled": 0,
    "upload-slots-per-torrent": 14,
    "utp-enabled": true
}
jeff@behemuth:/usr/local/bin$

x190
Posts: 5094
Joined: Sun Nov 30, 2008 4:59 am

Re: Script to change transmission listening port

Postby x190 » Thu Sep 10, 2015 3:16 pm

Why don't you set-up a user and password? Why the space after ""peer-port": 40696 ,"? You can't access the daemon unless ""rpc-enabled": false," is true! Is "192.168.1.1" the correct IP address?
The stone age didn’t end because we ran out of stones.
---The Great Disruption - by Paul Gilding
https://paulgilding.com/
-------------------------------------------------

plainzwalker
Posts: 6
Joined: Thu Sep 10, 2015 12:28 am

Re: Script to change transmission listening port

Postby plainzwalker » Thu Sep 10, 2015 4:04 pm

I disabled the user/pass because it wasn't working so I was testing with that. The space I didn't see. I think I disabled rpc as a troubleshooting step. As for 192.168.1.1 is the ip for pfsense router that runs a script that request the port forward from PIA.

x190
Posts: 5094
Joined: Sun Nov 30, 2008 4:59 am

Re: Script to change transmission listening port

Postby x190 » Thu Sep 10, 2015 7:16 pm

The idea was to get you to fix the source of your problem, starting with fixing your script (user:pass). Fill in the blanks --- don't just comment them out. Then fix your settings.json --- the one Transmission uses (see your Transmission log file).

http://trac.transmissionbt.com/wiki/ConfigFiles
https://trac.transmissionbt.com/wiki/UnixServer/Debian

https://trac.transmissionbt.com/wiki/Ed ... Files#Misc
message-level: Number (0 = None, 1 = Error, 2 = Info, 3 = Debug, default = 2) Set verbosity of transmission messages.

Search 'man transmission-daemon' for '--logfile', or ask your distributor, if you can't find a log file.
The stone age didn’t end because we ran out of stones.
---The Great Disruption - by Paul Gilding
https://paulgilding.com/
-------------------------------------------------

doonze
Posts: 4
Joined: Fri Jul 01, 2016 12:50 pm

Re: Script to change transmission listening port

Postby doonze » Fri Jul 01, 2016 1:19 pm

Here is a working python script I have to do exactly what you are wanting, but it only works on PIA VPN. There are some other particulars, like you have to use a PIA server that supports it. The US ones don't at this time.

I have a Pi2, Raspbian 8 "Jessie" and the latest transmission from the repository. Works great....

I have it set to run every hour with a cron job, so if my port changes it will update the port accordingly.

Code: Select all

#!/usr/bin/env python

import urllib
import urllib2
import json
import sys
import netifaces
import os

# put your VPN username and password below
YOUR_USERNAME = "XXXXXXXX"
YOUR_PASSWORD = "XXXXXXXX"

# This should be a long random string, or something that no one else is going
# to be able to guess.  Don't share this amongst multiple computers on the
# same VPN account.  If you have more than one computer, use a different client
# ID for each.  I recommende the output of the Linux "uuidgen" command, but
# you can really just use whatever.
YOUR_CLIENT_ID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

# The interface your VPN uses.  We use this to look up your local IP, as
# required by the port forwarding API.  Probably you won't have to change this
# unless you really know what you're doing (e.g., if you have more than one
# VPN tunnel on the same system or something)
VPN_IFACE = "tun0"

# This is the API URL.  Don't change this.
API_URL = "https://www.privateinternetaccess.com/vpninfo/port_forward_assignment"

# Look up the local IP from the VPN interface
try:
    local_ip =  netifaces.ifaddresses(VPN_IFACE)[netifaces.AF_INET][0]["addr"]
except ValueError,e:
    print "No such interface.  Are you connected?"
    sys.exit(-1)

# Make the API request to the webserver
request = urllib2.Request(API_URL, urllib.urlencode(
        {
            "user":YOUR_USERNAME,
            "pass":YOUR_PASSWORD,
            "client_id":YOUR_CLIENT_ID,
            "local_ip":local_ip
            }
        ))

# Gather the (possibly multi-line) JSON response and create a python dict
# out of it
response = ""
for line in urllib2.urlopen(request).readlines():
    response += line
resp =  json.loads(response)

# Now either print out the forwarded port or an error message.
if "port" in resp:
    print resp["port"]
    port = resp["port"]
    cmdstring = 'transmission-remote -n "userXXXXX:passXXXXX" -p %d' % port
    os.system(cmdstring)
elif "error" in resp:
    print "Error: %s" % resp["error"]
    sys.exit(-1)
else:
    print "Error: no idea what failed!"
    sys.exit(-2)


Of course, you have to add your own passwords and usernames where needed. Look for XXXXX's in the above. And I can't promise on some systems you won't have to tweek it. This is a copy of a script on the PIA forums, in it's original form it just printed out the port, I added the bits about auto-updating transmission with the info. This is the bits I added.


Code: Select all

 port = resp["port"]
    cmdstring = 'transmission-remote -n "userXXXXX:passXXXXX" -p %d' % port
    os.system(cmdstring)


and this at the top:

Code: Select all

import os


Here is the cron I created to run it:

Code: Select all

0 * * * *          /usr/bin/python ~/vpnport.py >> /home/pi/log/vpnport.log 2>&1


You want that little logging piece on the end, every hour it spits out the "success" message from transmission, and the port the script spits out, so you know what it is trying to change it to. If you just use system log, only the transmission bit makes it to the syslog. The print pieces of the script are lost, and you want those if there are issues.

I didn't write this script, so I don't know a whole lot about it aside from the bits I added. It worked "out of the box" for me, so I never had to mess with the original.


Return to “GTK+ Support”