Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Wrapper to bind Transmission to the IP for a VPN interface on Linux or refuse to start on failure
#!/usr/bin/env python
"""Simple wrapper to update Transmission's IPv4 binding on startup for use with VPNs.
(For Linux systems. Tested on Ubuntu 14.04 LTS)
"""
import json, os, subprocess
VPN_IF = "tun0"
TRANSMISSION_CFG = os.path.expanduser('~/.config/transmission/settings.json')
def get_iface_ipv4(interface):
# Call ifconfig for information. Exception if there is no such interface.
if_ip = subprocess.check_output(['ifconfig', interface])
# Extract the interface's IPv4 address. Die with an exception if there is
# none. (ie. if the interface isn't up)
return [x.split(':')[1].split()[0].strip() for x in if_ip.split('\n')
if 'inet addr:' in x][0]
def set_transmission_iface(interface):
try:
vpn_ip = get_iface_ipv4(interface)
except Exception:
subprocess.call(['zenity', '--error', '--text',
'VPN not found.\nNot starting torrent client.'])
raise
try:
with open(TRANSMISSION_CFG, 'r') as fobj:
config = json.load(fobj)
config['bind-address-ipv4'] = vpn_ip
with open(TRANSMISSION_CFG, 'w') as fobj:
json.dump(config, fobj, indent=2)
except Exception:
subprocess.call(['zenity', '--error', '--text',
'Could not update Transmission configuration.\n'
'Not starting torrent client.'])
raise
if __name__ == '__main__':
set_transmission_iface(VPN_IF)
os.execlp('transmission-gtk', 'transmission-gtk')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment