-#!/usr/bin/python
+#!/usr/bin/python2
import sys
try:
- needle = sys.argv[1]
- haystack = sys.argv[2]
+ needle = sys.argv[1]
+ haystack = sys.argv[2]
except IndexError:
- print >>sys.stderr, "Usage: %s needle haystack" % sys.argv[0]
- sys.exit(1)
+ print >>sys.stderr, "Usage: %s needle haystack" % sys.argv[0]
+ sys.exit(1)
f = open(needle)
count = 0
buf = ""
while True:
- newbuf = f.read(chunk_size)
- if not newbuf:
- break
- buf += newbuf
- pos = buf.find(magic)
- if pos >= 0:
- print "found", count + pos
- count += len(buf) - len(magic)
- buf = buf[-len(magic):]
+ newbuf = f.read(chunk_size)
+ if not newbuf:
+ break
+ buf += newbuf
+ pos = buf.find(magic)
+ if pos >= 0:
+ print "found", count + pos
+ count += len(buf) - len(magic)
+ buf = buf[-len(magic):]
f.close()
-#!/usr/bin/env python
+#!/usr/bin/python2
import random, string, sys
full_chars = alnum_chars * 2 + list("!@#%^&*(){}[]/=?+_-;:,.<>")
def generate(chars, length):
- return "".join([random.choice(chars) for i in xrange(length)])
+ return "".join([random.choice(chars) for i in xrange(length)])
def print_usage():
- print "Usage: %s [length] [alnum|full]" % sys.argv[0]
- sys.exit(1)
+ print "Usage: %s [length] [alnum|full]" % sys.argv[0]
+ sys.exit(1)
if __name__ == "__main__":
- if len(sys.argv) <= 1:
- n = 20
- elif sys.argv[1].isdigit():
- n = int(sys.argv[1])
- else:
- print_usage()
-
- if len(sys.argv) <= 2:
- chars = alnum_chars
- elif sys.argv[2] == "alnum":
- chars = alnum_chars
- elif sys.argv[2] == "full":
- chars = full_chars
- else:
- print_usage()
-
- print generate(chars, n)
+ if len(sys.argv) <= 1:
+ n = 20
+ elif sys.argv[1].isdigit():
+ n = int(sys.argv[1])
+ else:
+ print_usage()
+
+ if len(sys.argv) <= 2:
+ chars = alnum_chars
+ elif sys.argv[2] == "alnum":
+ chars = alnum_chars
+ elif sys.argv[2] == "full":
+ chars = full_chars
+ else:
+ print_usage()
+
+ print generate(chars, n)
-#!/usr/bin/env python
+#!/usr/bin/python2
"""
sendmailish python program.
# vim:ft=python
smtpServers = [
- SMTPProxy(remoteServer='mail.internode.on.net', domainSuffix='.internode.on.net'),
- SMTPProxy(remoteServer='smtp.usyd.edu.au', domainSuffix='.usyd.edu.au'),
- SMTPProxy(remoteServer='mail.iinet.net.au', domainSuffix='.iinet.net.au'),
- SMTPProxy(remoteServer='mail.netspace.net.au', domainSuffix='.netspace.net.au'),
- SMTPProxy(remoteServer='mail.optusnet.com.au', domainSuffix='.optusnet.com.au'),
- SMTPProxySSH(remoteServer='delx.net.au', remoteSendmail='/usr/sbin/sendmail'),
+ SMTPProxy(remoteServer='mail.internode.on.net', domainSuffix='.internode.on.net'),
+ SMTPProxy(remoteServer='smtp.usyd.edu.au', domainSuffix='.usyd.edu.au'),
+ SMTPProxy(remoteServer='mail.iinet.net.au', domainSuffix='.iinet.net.au'),
+ SMTPProxy(remoteServer='mail.netspace.net.au', domainSuffix='.netspace.net.au'),
+ SMTPProxy(remoteServer='mail.optusnet.com.au', domainSuffix='.optusnet.com.au'),
+ SMTPProxySSH(remoteServer='delx.net.au', remoteSendmail='/usr/sbin/sendmail'),
]
myIPURL = "http://suits.ug.it.usyd.edu.au/myip.php"
import logging
try:
- # Attempt to load this debugging decorator function
- from decorators import logCall
+ # Attempt to load this debugging decorator function
+ from decorators import logCall
except ImportError:
- def logCall(f):
- '''This is a no-op decorator function'''
- return f
+ def logCall(f):
+ '''This is a no-op decorator function'''
+ return f
class SMTPProxyBase(object):
- def __repr__(self):
- return '%s(%s)' % (self.__class__.__name__,
- ', '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__)
- )
+ def __repr__(self):
+ return '%s(%s)' % (
+ self.__class__.__name__,
+ ', '.join('%s=%r' % (k, getattr(self, k)) for k in self.__slots__)
+ )
class SMTPProxy(SMTPProxyBase):
- __slots__ = (
- 'remoteServer',
- 'domainSuffix',
- 'username',
- 'password',
- 'useSSL',
- )
- @logCall
- def __init__(self, remoteServer, domainSuffix, username=None, password=None, useSSL=False):
- self.remoteServer = remoteServer
- self.domainSuffix = domainSuffix
-
- self.username = username
- self.password = password
- self.useSSL = useSSL
-
- def doesHandle(self, localhostName):
- '''Determines if this SMTPProxy can be used within this domain'''
- if localhostName is None:
- return False
- else:
- return localhostName.endswith(self.domainSuffix)
-
- def sendmail(self, fromAddr, toAddrs, message):
- '''
- Actually send the mail.
-
- Returns true if the mail was successfully send
- '''
-
- smtp = smtplib.SMTP(self.remoteServer)
- if self.useSSL:
- smtp.starttls()
- if self.username is not None and self.password is not None:
- smtp.login(self.username, self.password)
- smtp.sendmail(fromAddr, toAddrs, message)
- smtp.quit()
- return True
+ __slots__ = (
+ 'remoteServer',
+ 'domainSuffix',
+ 'username',
+ 'password',
+ 'useSSL',
+ )
+ @logCall
+ def __init__(self, remoteServer, domainSuffix, username=None, password=None, useSSL=False):
+ self.remoteServer = remoteServer
+ self.domainSuffix = domainSuffix
+
+ self.username = username
+ self.password = password
+ self.useSSL = useSSL
+
+ def doesHandle(self, localhostName):
+ '''Determines if this SMTPProxy can be used within this domain'''
+ if localhostName is None:
+ return False
+ else:
+ return localhostName.endswith(self.domainSuffix)
+
+ def sendmail(self, fromAddr, toAddrs, message):
+ '''
+ Actually send the mail.
+
+ Returns true if the mail was successfully send
+ '''
+
+ smtp = smtplib.SMTP(self.remoteServer)
+ if self.useSSL:
+ smtp.starttls()
+ if self.username is not None and self.password is not None:
+ smtp.login(self.username, self.password)
+ smtp.sendmail(fromAddr, toAddrs, message)
+ smtp.quit()
+ return True
class SMTPProxySSH(SMTPProxyBase):
- __slots__ = ('remoteServer',)
- @logCall
- def __init__(self, remoteServer, remoteSendmail):
- self.remoteServer = remoteServer
- self.remoteSendmail = remoteSendmail
-
- def doesHandle(self, *args, **kwargs):
- '''
- Determines if this SMTPProxySSH can be used within this domain.
- Note: This method returns true for all values.
- '''
- return True
-
- def sendmail(self, fromAddr, toAddrs, message):
- '''
- Actually send the mail.
-
- Returns true if the mail was successfully send
- '''
- cmdline = ['ssh', self.remoteServer, self.remoteSendmail, '--']
- cmdline.extend(toAddrs)
- process = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
- process.communicate(message)
- return not bool(process.wait())
+ __slots__ = ('remoteServer',)
+ @logCall
+ def __init__(self, remoteServer, remoteSendmail):
+ self.remoteServer = remoteServer
+ self.remoteSendmail = remoteSendmail
+
+ def doesHandle(self, *args, **kwargs):
+ '''
+ Determines if this SMTPProxySSH can be used within this domain.
+ Note: This method returns true for all values.
+ '''
+ return True
+
+ def sendmail(self, fromAddr, toAddrs, message):
+ '''
+ Actually send the mail.
+
+ Returns true if the mail was successfully send
+ '''
+ cmdline = ['ssh', self.remoteServer, self.remoteSendmail, '--']
+ cmdline.extend(toAddrs)
+ process = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
+ process.communicate(message)
+ return not bool(process.wait())
def getOptionParser():
- parser = optparse.OptionParser(usage="%prog [options] toAddress1 [toAddress2] ...")
- parser.add_option('--debug',
- action='store_const', dest='debugLevel', const=logging.DEBUG,
- help='Sets the logging level to debug')
- parser.add_option('--warn',
- action='store_const', dest='debugLevel', const=logging.WARNING,
- help='Sets the logging level to warn')
- parser.set_default('debugLevel', logging.ERROR)
+ parser = optparse.OptionParser(usage="%prog [options] toAddress1 [toAddress2] ...")
+ parser.add_option('--debug',
+ action='store_const', dest='debugLevel', const=logging.DEBUG,
+ help='Sets the logging level to debug')
+ parser.add_option('--warn',
+ action='store_const', dest='debugLevel', const=logging.WARNING,
+ help='Sets the logging level to warn')
+ parser.set_default('debugLevel', logging.ERROR)
- return parser
+ return parser
def main():
- # Load the config file
- try:
- exec(open(os.path.expanduser('~/.sendmailpyrc'), 'r').read())
- except Exception, e:
- print >>sys.stderr, 'Error with config file:', e
- return False
-
- # Get the to addresses
- parser = getOptionParser()
- options, toAddrs = parser.parse_args()
- logging.basicConfig(level=options.debugLevel)
- if not toAddrs:
- parser.error('No to addresses found')
-
- # Pick a SMTP server
- try:
- host = urllib.urlopen(myIPURL).read().strip()
- except:
- host = None
- logging.exception('Failed to grab our external domain name')
-
- for smtpProxy in smtpServers:
- if smtpProxy.doesHandle(host):
- # Got the correct smtpServer
- logging.info('Using the Proxy %r to connect from %s', smtpProxy, host)
- break
- else:
- logging.error('Did not find a proxy to connect from %s', host)
- return False
-
- # Get the from address
- message = sys.stdin.read()
- fromAddr = email.message_from_string(message)["from"]
- _, fromAddr = email.utils.parseaddr(fromAddr)
-
- return smtpProxy.sendmail(fromAddr, toAddrs, message)
+ # Load the config file
+ try:
+ exec(open(os.path.expanduser('~/.sendmailpyrc'), 'r').read())
+ except Exception, e:
+ print >>sys.stderr, 'Error with config file:', e
+ return False
+
+ # Get the to addresses
+ parser = getOptionParser()
+ options, toAddrs = parser.parse_args()
+ logging.basicConfig(level=options.debugLevel)
+ if not toAddrs:
+ parser.error('No to addresses found')
+
+ # Pick a SMTP server
+ try:
+ host = urllib.urlopen(myIPURL).read().strip()
+ except:
+ host = None
+ logging.exception('Failed to grab our external domain name')
+
+ for smtpProxy in smtpServers:
+ if smtpProxy.doesHandle(host):
+ # Got the correct smtpServer
+ logging.info('Using the Proxy %r to connect from %s', smtpProxy, host)
+ break
+ else:
+ logging.error('Did not find a proxy to connect from %s', host)
+ return False
+
+ # Get the from address
+ message = sys.stdin.read()
+ fromAddr = email.message_from_string(message)["from"]
+ _, fromAddr = email.utils.parseaddr(fromAddr)
+
+ return smtpProxy.sendmail(fromAddr, toAddrs, message)
if __name__ == "__main__":
- # Specify SMTP servers here
- sys.exit(not main())
+ # Specify SMTP servers here
+ sys.exit(not main())
(
# Only allow one backup to run at a time
if ! flock -n -x 200; then
- echo "Failed to get a lock!"
- exit 1
+ echo "Failed to get a lock!"
+ exit 1
fi
# Exclude other filesystems from the backup. This leaves only the files we
# want, on the root file system, to back up.
# Also exclude other large collections of files which we don't care to save.
rdiff-backup \
- --preserve-numerical-ids \
- --exclude-sockets \
- --exclude '/home/*/tmp' \
- --include '/home' \
- --exclude '/backup' \
- --exclude '/tmp' \
- --exclude '/var/cache' \
- --exclude '/var/log' \
- --include '/var' \
- --exclude-other-filesystems \
- / /backup/
+ --preserve-numerical-ids \
+ --exclude-sockets \
+ --exclude '/home/*/tmp' \
+ --include '/home' \
+ --exclude '/backup' \
+ --exclude '/tmp' \
+ --exclude '/var/cache' \
+ --exclude '/var/log' \
+ --include '/var' \
+ --exclude-other-filesystems \
+ / /backup/
# Remove old backups to free up some space
Example configuration:
{
- "apn": "internet",
- "bluetooth_addr": "DE:AD:BE:EE:EE:EF",
- "bluetooth_channel": "22"
+ "apn": "internet",
+ "bluetooth_addr": "DE:AD:BE:EE:EE:EF",
+ "bluetooth_channel": "22"
}
"""
class DiallerException(Exception):
- pass
+ pass
class BluetoothDialler(object):
- def __init__(self, rfcomm_id, bt_addr, bt_channel, apn):
- self.rfcomm_id = rfcomm_id
- self.bt_addr = bt_addr
- self.bt_channel = bt_channel
- self.apn = apn
-
- self.rfcomm = None
- self.wvdial = None
- self.wvdial_conf_name = None
- self.dbus_system = None
-
- def release(self):
- if self.wvdial:
- try:
- self.wvdial.terminate()
- self.wvdial.wait()
- except Exception as e:
- print(e)
-
- if self.rfcomm:
- try:
- self.rfcomm.terminate()
- self.rfcomm.wait()
- except Exception as e:
- print(e)
-
- if self.wvdial_conf_name:
- try:
- os.unlink(self.wvdial_conf_name)
- except Exception as e:
- print(e)
-
- try:
- reset_rfcomm(self.rfcomm_id)
- except Exception as e:
- print(e)
-
- if self.dbus_system:
- try:
- self.disconnect_bluetooth()
- except Exception as e:
- print(e)
-
-
- def setup_dbus(self):
- self.dbus_system = dbus.SystemBus()
-
- def enable_bluetooth(self):
- bluez = self.dbus_system.get_object("org.bluez", "/org/bluez/hci0")
- iprops = dbus.Interface(bluez, "org.freedesktop.DBus.Properties")
- iprops.Set("org.bluez.Adapter1", "Powered", True)
-
- def disconnect_bluetooth(self):
- path = self.bt_addr.upper().replace(":", "_")
- bluez_dev = self.dbus_system.get_object("org.bluez", "/org/bluez/hci0/dev_" + path)
- idev = dbus.Interface(bluez_dev, "org.bluez.Device1")
- idev.Disconnect()
-
- def connect_rfcomm(self):
- self.rfcomm = subprocess.Popen([
- "rfcomm",
- "connect",
- self.rfcomm_id,
- self.bt_addr,
- self.bt_channel,
- ])
-
- # poll until connected
- start = time.time()
- while time.time() - start < 10:
- if self.is_rfcomm_connected():
- return
- time.sleep(0.1)
- raise DiallerException("Timeout connecting rfcomm")
-
- def is_rfcomm_connected(self):
- output = subprocess.check_output(["rfcomm", "-a"])
- for line in output.decode("ascii").split("\n"):
- if not line.startswith("rfcomm%s:" % self.rfcomm_id):
- continue
- if line.find(" connected ") >= 0:
- return True
- return False
-
- def write_wvdial_conf(self):
- fd, self.wvdial_conf_name = tempfile.mkstemp()
- f = os.fdopen(fd, "w")
- f.write("""
+ def __init__(self, rfcomm_id, bt_addr, bt_channel, apn):
+ self.rfcomm_id = rfcomm_id
+ self.bt_addr = bt_addr
+ self.bt_channel = bt_channel
+ self.apn = apn
+
+ self.rfcomm = None
+ self.wvdial = None
+ self.wvdial_conf_name = None
+ self.dbus_system = None
+
+ def release(self):
+ if self.wvdial:
+ try:
+ self.wvdial.terminate()
+ self.wvdial.wait()
+ except Exception as e:
+ print(e)
+
+ if self.rfcomm:
+ try:
+ self.rfcomm.terminate()
+ self.rfcomm.wait()
+ except Exception as e:
+ print(e)
+
+ if self.wvdial_conf_name:
+ try:
+ os.unlink(self.wvdial_conf_name)
+ except Exception as e:
+ print(e)
+
+ try:
+ reset_rfcomm(self.rfcomm_id)
+ except Exception as e:
+ print(e)
+
+ if self.dbus_system:
+ try:
+ self.disconnect_bluetooth()
+ except Exception as e:
+ print(e)
+
+
+ def setup_dbus(self):
+ self.dbus_system = dbus.SystemBus()
+
+ def enable_bluetooth(self):
+ bluez = self.dbus_system.get_object("org.bluez", "/org/bluez/hci0")
+ iprops = dbus.Interface(bluez, "org.freedesktop.DBus.Properties")
+ iprops.Set("org.bluez.Adapter1", "Powered", True)
+
+ def disconnect_bluetooth(self):
+ path = self.bt_addr.upper().replace(":", "_")
+ bluez_dev = self.dbus_system.get_object("org.bluez", "/org/bluez/hci0/dev_" + path)
+ idev = dbus.Interface(bluez_dev, "org.bluez.Device1")
+ idev.Disconnect()
+
+ def connect_rfcomm(self):
+ self.rfcomm = subprocess.Popen([
+ "rfcomm",
+ "connect",
+ self.rfcomm_id,
+ self.bt_addr,
+ self.bt_channel,
+ ])
+
+ # poll until connected
+ start = time.time()
+ while time.time() - start < 10:
+ if self.is_rfcomm_connected():
+ return
+ time.sleep(0.1)
+ raise DiallerException("Timeout connecting rfcomm")
+
+ def is_rfcomm_connected(self):
+ output = subprocess.check_output(["rfcomm", "-a"])
+ for line in output.decode("ascii").split("\n"):
+ if not line.startswith("rfcomm%s:" % self.rfcomm_id):
+ continue
+ if line.find(" connected ") >= 0:
+ return True
+ return False
+
+ def write_wvdial_conf(self):
+ fd, self.wvdial_conf_name = tempfile.mkstemp()
+ f = os.fdopen(fd, "w")
+ f.write("""
[Dialer Defaults]
Modem = /dev/rfcomm0
Baud = 115200
Username = dummy
Password = dummy
""" % self.apn)
- f.close()
+ f.close()
- def connect_wvdial(self):
- self.wvdial = subprocess.Popen([
- "wvdial", "-C", self.wvdial_conf_name
- ])
- self.wvdial.wait()
+ def connect_wvdial(self):
+ self.wvdial = subprocess.Popen([
+ "wvdial", "-C", self.wvdial_conf_name
+ ])
+ self.wvdial.wait()
- def run(self):
- try:
- self.setup_dbus()
+ def run(self):
+ try:
+ self.setup_dbus()
- print("Enabling bluetooth...")
- self.enable_bluetooth()
+ print("Enabling bluetooth...")
+ self.enable_bluetooth()
- print("Connecting rfcomm...")
- self.connect_rfcomm()
- self.write_wvdial_conf()
+ print("Connecting rfcomm...")
+ self.connect_rfcomm()
+ self.write_wvdial_conf()
- print("Dialling...")
- self.connect_wvdial()
+ print("Dialling...")
+ self.connect_wvdial()
- except KeyboardInterrupt as e:
- print("Exiting...")
- except DiallerException as e:
- print(e)
- finally:
- self.release()
+ except KeyboardInterrupt as e:
+ print("Exiting...")
+ except DiallerException as e:
+ print(e)
+ finally:
+ self.release()
def get_next_rfcomm_id():
- # for now always use rfcomm0
- reset_rfcomm("all")
- return "0"
+ # for now always use rfcomm0
+ reset_rfcomm("all")
+ return "0"
def reset_rfcomm(rfcomm_id):
- subprocess.call(["rfcomm", "release", rfcomm_id], stderr=open("/dev/null"))
+ subprocess.call(["rfcomm", "release", rfcomm_id], stderr=open("/dev/null"))
def read_config(filename):
- try:
- config = open(os.path.expanduser(filename))
- except OSError as e:
- print("Failed to open config file: %s" % e)
- sys.exit(1)
+ try:
+ config = open(os.path.expanduser(filename))
+ except OSError as e:
+ print("Failed to open config file: %s" % e)
+ sys.exit(1)
- try:
- return json.load(config)
- except ValueError as e:
- print("Failed to parse config file %s: %s" % (filename, e))
- sys.exit(1)
+ try:
+ return json.load(config)
+ except ValueError as e:
+ print("Failed to parse config file %s: %s" % (filename, e))
+ sys.exit(1)
def main():
- rfcomm_id = get_next_rfcomm_id()
- config = read_config("~/.config/bt-dun-connect.json")
- dialler = BluetoothDialler(
- rfcomm_id=rfcomm_id,
- bt_addr=config["bluetooth_addr"],
- bt_channel=config["bluetooth_channel"],
- apn=config["apn"],
- )
- dialler.run()
+ rfcomm_id = get_next_rfcomm_id()
+ config = read_config("~/.config/bt-dun-connect.json")
+ dialler = BluetoothDialler(
+ rfcomm_id=rfcomm_id,
+ bt_addr=config["bluetooth_addr"],
+ bt_channel=config["bluetooth_channel"],
+ apn=config["apn"],
+ )
+ dialler.run()
if __name__ == "__main__":
- main()
+ main()
-#!/usr/bin/python
+#!/usr/bin/python2
from __future__ import division
import sys
def pp_size(size):
- suffixes = ["", "KiB", "MiB", "GiB"]
- for i, suffix in enumerate(suffixes):
- if size < 1024:
- break
- size /= 1024
- return "%.2f %s" % (size, suffix)
+ suffixes = ["", "KiB", "MiB", "GiB"]
+ for i, suffix in enumerate(suffixes):
+ if size < 1024:
+ break
+ size /= 1024
+ return "%.2f %s" % (size, suffix)
def check_path(path):
- stat = os.statvfs(path)
- total = stat.f_bsize * stat.f_blocks
- free = stat.f_bsize * stat.f_bavail
- warn = False
+ stat = os.statvfs(path)
+ total = stat.f_bsize * stat.f_blocks
+ free = stat.f_bsize * stat.f_bavail
+ warn = False
- if total < 5*1024*1024*1024:
- if free < total * 0.05:
- warn = True
- elif free < 2*1024*1024*1024:
- warn = True
+ if total < 5*1024*1024*1024:
+ if free < total * 0.05:
+ warn = True
+ elif free < 2*1024*1024*1024:
+ warn = True
- if warn:
- print "WARNING! %s has only %s remaining" % (path, pp_size(free))
+ if warn:
+ print "WARNING! %s has only %s remaining" % (path, pp_size(free))
def main():
- paths = sys.argv[1:]
- if not paths:
- print >>sys.stderr, "Usage: %s path" % sys.argv[0]
- sys.exit(1)
- for path in paths:
- check_path(path)
+ paths = sys.argv[1:]
+ if not paths:
+ print >>sys.stderr, "Usage: %s path" % sys.argv[0]
+ sys.exit(1)
+ for path in paths:
+ check_path(path)
if __name__ == "__main__":
- main()
+ main()
# Preflight checks #
####################
-if [ "$(lsb_release -r | cut -d ':' -f 2 | tr -d ' ')" != "$RELEASE" ]; then
- echo "Sorry, at the moment this script only supports Ubuntu $RELEASE"
- exit 1
+if [ "$(lsb_release -r | cut -d ':' -f 2 | tr -d ' ')" != "$RELEASE" ]; then
+ echo "Sorry, at the moment this script only supports Ubuntu $RELEASE"
+ exit 1
fi
if ! grep -q universe /etc/apt/sources.list /etc/apt/sources.list.d/*.list; then
- echo "You must enable universe in your apt sources.list"
- exit 1
+ echo "You must enable universe in your apt sources.list"
+ exit 1
fi
if ! grep -q multiverse /etc/apt/sources.list /etc/apt/sources.list.d/*.list; then
- echo "You must enable multiverse in your apt sources.list"
- exit 1
+ echo "You must enable multiverse in your apt sources.list"
+ exit 1
fi
if ! which equivs-build > /dev/null; then
- sudo apt-get install equivs
+ sudo apt-get install equivs
fi
EOT
function get_line {
- line="$(apt-cache show ubuntu-desktop | grep "$1:")"
- for pkg in $EXCLUDE; do
- line="$(echo "$line" | sed -e "s/$pkg, //" -e "s/, $pkg\$//")"
- done
- echo -n "$line"
+ line="$(apt-cache show ubuntu-desktop | grep "$1:")"
+ for pkg in $EXCLUDE; do
+ line="$(echo "$line" | sed -e "s/$pkg, //" -e "s/, $pkg\$//")"
+ done
+ echo -n "$line"
}
(
-#!/usr/bin/env python
+#!/usr/bin/python2
from datetime import datetime
import os
def increment_serial(line):
- current_serial = re.search(R"\b\d\d*\b", line).group(0)
+ current_serial = re.search(R"\b\d\d*\b", line).group(0)
- current = int(current_serial)
- current_num = current % 100
- current_date = (current - current_num) / 100
- new_date = int(datetime.now().strftime("%Y%m%d"))
- if current_date == new_date:
- next_num = current_num + 1
- else:
- next_num = 0
+ current = int(current_serial)
+ current_num = current % 100
+ current_date = (current - current_num) / 100
+ new_date = int(datetime.now().strftime("%Y%m%d"))
+ if current_date == new_date:
+ next_num = current_num + 1
+ else:
+ next_num = 0
- if next_num >= 100:
- raise ValueError("Too many serial changes today!")
- new_serial = str(new_date) + str(next_num).zfill(2)
- line = line.replace(current_serial, new_serial)
+ if next_num >= 100:
+ raise ValueError("Too many serial changes today!")
+ new_serial = str(new_date) + str(next_num).zfill(2)
+ line = line.replace(current_serial, new_serial)
- return line
+ return line
def replace_ip(line):
- source_ip, source_port, dest_ip, dest_port = os.environ["SSH_CONNECTION"].split()
- line = re.sub(R"\b\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?\b", source_ip, line)
- return line
+ source_ip, source_port, dest_ip, dest_port = os.environ["SSH_CONNECTION"].split()
+ line = re.sub(R"\b\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?\b", source_ip, line)
+ return line
def main(live, zonefile, dnslabel):
- f = open(zonefile)
- out = []
- for line in f:
- if line.find("Serial") >= 0:
- out.append(increment_serial(line))
- elif line.find("DYNDNS") >= 0 and line.find("bnet") >= 0:
- out.append(replace_ip(line))
- else:
- out.append(line)
-
- f.close()
-
- if live:
- outf = open(zonefile, "w")
- outf.writelines(out)
- outf.close()
- subprocess.check_call(["sudo", "/etc/init.d/bind9", "reload"])
- else:
- sys.stdout.writelines(out)
+ f = open(zonefile)
+ out = []
+ for line in f:
+ if line.find("Serial") >= 0:
+ out.append(increment_serial(line))
+ elif line.find("DYNDNS") >= 0 and line.find("bnet") >= 0:
+ out.append(replace_ip(line))
+ else:
+ out.append(line)
+
+ f.close()
+
+ if live:
+ outf = open(zonefile, "w")
+ outf.writelines(out)
+ outf.close()
+ subprocess.check_call(["sudo", "/etc/init.d/bind9", "reload"])
+ else:
+ sys.stdout.writelines(out)
if __name__ == "__main__":
- live = False
- try:
- i = 1
- if sys.argv[1] == "live":
- live = True
- i = 2
- zonefile = sys.argv[i]
- dnslabel = sys.argv[i+1]
- except:
- print >>sys.stderr, "Usage: %s [go] zonefile dnslabel" % sys.argv[0]
- sys.exit(1)
-
- main(live, zonefile, dnslabel)
+ live = False
+ try:
+ i = 1
+ if sys.argv[1] == "live":
+ live = True
+ i = 2
+ zonefile = sys.argv[i]
+ dnslabel = sys.argv[i+1]
+ except:
+ print >>sys.stderr, "Usage: %s [go] zonefile dnslabel" % sys.argv[0]
+ sys.exit(1)
+
+ main(live, zonefile, dnslabel)
-#!/usr/bin/python
+#!/usr/bin/python2
import cherrypy
import os
import webbrowser
class Listener(object):
- @cherrypy.expose
- def firefox(self, url):
- print "Loading:", url
- webbrowser.open(url)
- raise cherrypy.HTTPRedirect(url, status=303)
+ @cherrypy.expose
+ def firefox(self, url):
+ print "Loading:", url
+ webbrowser.open(url)
+ raise cherrypy.HTTPRedirect(url, status=303)
def do_fork():
- pid = os.fork()
- if pid < 0:
- print >>sys.stderr, "Unable to fork!"
- sys.exit(1)
- if pid != 0:
- sys.exit(0)
+ pid = os.fork()
+ if pid < 0:
+ print >>sys.stderr, "Unable to fork!"
+ sys.exit(1)
+ if pid != 0:
+ sys.exit(0)
def main(fork):
- if fork:
- do_fork()
- cherrypy.tree.mount(Listener())
- cherrypy.server.socket_host = "0.0.0.0"
- cherrypy.server.socket_port = 8080
- cherrypy.engine.start()
+ if fork:
+ do_fork()
+ cherrypy.tree.mount(Listener())
+ cherrypy.server.socket_host = "0.0.0.0"
+ cherrypy.server.socket_port = 8080
+ cherrypy.engine.start()
if __name__ == "__main__":
- fork = False
- if len(sys.argv) != 1:
- if sys.argv[1] == "--fork":
- fork = True
- else:
- print >>sys.stderr, "Usage: %s [--fork]" % sys.argv[0]
- sys.exit(1)
- main(fork)
+ fork = False
+ if len(sys.argv) != 1:
+ if sys.argv[1] == "--fork":
+ fork = True
+ else:
+ print >>sys.stderr, "Usage: %s [--fork]" % sys.argv[0]
+ sys.exit(1)
+ main(fork)
set -e
if [ -z "$1" ]; then
- echo "Usage: $0 /path/to/videos [new-link-dir] [num_days]"
- exit 1
+ echo "Usage: $0 /path/to/videos [new-link-dir] [num_days]"
+ exit 1
fi
watch_dir="$1"
find "$watch_dir/-NEW-" -type l -delete
find "$watch_dir" -type f -mtime "-${num_days}" |
- while read line; do
- if basename "$line" | grep -q '^\.'; then
- continue
- fi
- linkname="$(echo "$line" | sed -e "s|$watch_dir/||" -e "s|/| - |g")"
- ln -s "$line" "$watch_dir/-NEW-/$linkname"
- done
+ while read line; do
+ if basename "$line" | grep -q '^\.'; then
+ continue
+ fi
+ linkname="$(echo "$line" | sed -e "s|$watch_dir/||" -e "s|/| - |g")"
+ ln -s "$line" "$watch_dir/-NEW-/$linkname"
+ done
(
if ! flock -w 10 -x 200; then
- echo "Failed to get a lock!"
- exit 1
+ echo "Failed to get a lock!"
+ exit 1
fi
echo "got lock"
# Unmute everything and turn volume to full
if [ "$1" = "--max-volume" ]; then
- echo "max volume"
- max_volume=1
- shift
- pacmd 'dump' | grep 'set-sink' > "$PULSESTATE"
- cat "$PULSESTATE" | grep 'set-sink-mute' | awk '{print $2;}' | \
- while read device; do
- pacmd "set-sink-volume $device 0x10000" > /dev/null
- pacmd "set-sink-mute $device no" > /dev/null
- done
+ echo "max volume"
+ max_volume=1
+ shift
+ pacmd 'dump' | grep 'set-sink' > "$PULSESTATE"
+ cat "$PULSESTATE" | grep 'set-sink-mute' | awk '{print $2;}' | \
+ while read device; do
+ pacmd "set-sink-volume $device 0x10000" > /dev/null
+ pacmd "set-sink-mute $device no" > /dev/null
+ done
fi
# Switch volume keys to F9/F10 with xmodmap
if [ "$1" = "--switch-volume-keys" ]; then
- echo "switch volume"
- switch_volume=1
- shift
- xmodmap -e 'keycode 122 = F9'
- xmodmap -e 'keycode 123 = F10'
+ echo "switch volume"
+ switch_volume=1
+ shift
+ xmodmap -e 'keycode 122 = F9'
+ xmodmap -e 'keycode 123 = F10'
fi
# Restore volume levels and mute status
if [ -n "$max_volume" ]; then
- cat "$PULSESTATE" | pacmd > /dev/null
+ cat "$PULSESTATE" | pacmd > /dev/null
fi
# Restore volume keys
if [ -n "$switch_volume" ]; then
- xmodmap -e 'keycode 122 = XF86AudioLowerVolume'
- xmodmap -e 'keycode 123 = XF86AudioRaiseVolume'
+ xmodmap -e 'keycode 122 = XF86AudioLowerVolume'
+ xmodmap -e 'keycode 123 = XF86AudioRaiseVolume'
fi
) 200>"$LOCKFILE"
# */5 * * * * $HOME/bin/monitor-dir /path/to/something
if [ -z "$1" ]; then
- echo "Usage $0 dir [monitor_file] [ls]"
- exit 1
+ echo "Usage $0 dir [monitor_file] [ls]"
+ exit 1
fi
mon="${2:-$1/.monitor_dir}"
mon_tmp="${mon}_tmp"
${3:-ls} "$1" > "$mon_tmp"
if [ -r "$mon" ] && ! cmp -s "$mon" "$mon_tmp" && [ -n "$(ls "$1")" ]; then
- comm -13 "$mon" "$mon_tmp"
+ comm -13 "$mon" "$mon_tmp"
fi
mv "$mon_tmp" "$mon"
-#!/usr/bin/python
+#!/usr/bin/python2
import MySQLdb
import os
# Remove any symlinks and empty dirs in the tree
for dirpath, dirnames, filenames in os.walk(".", topdown=False):
- for filename in filenames:
- filename = os.path.join(dirpath, filename)
- if os.path.islink(filename):
- os.unlink(filename)
- for dirname in dirnames:
- dirname = os.path.join(dirpath, dirname)
- os.rmdir(dirname)
+ for filename in filenames:
+ filename = os.path.join(dirpath, filename)
+ if os.path.islink(filename):
+ os.unlink(filename)
+ for dirname in dirnames:
+ dirname = os.path.join(dirpath, dirname)
+ os.rmdir(dirname)
# Connect to the MythTV database based on the MythTV config
config_values = {}
for line in open(os.path.expanduser("~/.mythtv/mysql.txt")):
- line = line.strip()
- if line and not line.startswith("#"):
- (key, value) = line.split("=")
- config_values[key] = value
+ line = line.strip()
+ if line and not line.startswith("#"):
+ (key, value) = line.split("=")
+ config_values[key] = value
db_connection = MySQLdb.connect(
- host = config_values["DBHostName"],
- user = config_values["DBUserName"],
- passwd = config_values["DBPassword"],
- db = config_values["DBName"]
+ host = config_values["DBHostName"],
+ user = config_values["DBUserName"],
+ passwd = config_values["DBPassword"],
+ db = config_values["DBName"]
)
cursor = db_connection.cursor(MySQLdb.cursors.DictCursor)
# Find the recordings directory
cursor.execute("""
- SELECT * FROM settings
- WHERE value='RecordFilePrefix' AND hostname='%s'
+ SELECT * FROM settings
+ WHERE value='RecordFilePrefix' AND hostname='%s'
""" % socket.gethostname())
recordingsdir = cursor.fetchone()["data"]
# Now find all the recordings we have at the moment
cursor.execute("""
- SELECT title, subtitle, starttime, basename, watched FROM recorded
+ SELECT title, subtitle, starttime, basename, watched FROM recorded
""")
for row in cursor:
- title = row["title"]
- starttime = str(row["starttime"]).replace(":", "-")
- subtitle = row["subtitle"]
- basename = row["basename"]
- watched = bool(row["watched"])
+ title = row["title"]
+ starttime = str(row["starttime"]).replace(":", "-")
+ subtitle = row["subtitle"]
+ basename = row["basename"]
+ watched = bool(row["watched"])
- title = unsafe.sub("", title)
- subtitle = unsafe.sub("", subtitle)
- extn = os.path.splitext(basename)[1]
+ title = unsafe.sub("", title)
+ subtitle = unsafe.sub("", subtitle)
+ extn = os.path.splitext(basename)[1]
- if subtitle:
- filename = "%s - %s%s" % (starttime, subtitle, extn)
- else:
- filename = "%s%s" % (starttime, extn)
- if watched:
- filename = "watched/" + filename
+ if subtitle:
+ filename = "%s - %s%s" % (starttime, subtitle, extn)
+ else:
+ filename = "%s%s" % (starttime, extn)
+ if watched:
+ filename = "watched/" + filename
- source = "%s/%s" % (recordingsdir, basename)
- dest = "%s/%s" % (title, filename)
+ source = "%s/%s" % (recordingsdir, basename)
+ dest = "%s/%s" % (title, filename)
- if not os.path.isfile(source):
- continue
+ if not os.path.isfile(source):
+ continue
- dirnames = dest.split("/")[:-1]
- for i in xrange(1, len(dirnames)+1):
- dirname = "/".join(dirnames[:i])
- if not os.path.isdir(dirname):
- os.mkdir(dirname)
+ dirnames = dest.split("/")[:-1]
+ for i in xrange(1, len(dirnames)+1):
+ dirname = "/".join(dirnames[:i])
+ if not os.path.isdir(dirname):
+ os.mkdir(dirname)
- os.symlink(source, dest)
+ os.symlink(source, dest)
-#!/usr/bin/env python
+#!/usr/bin/python2
"""
Proxy Utility
if sys.platform == "linux2":
- try:
- socket.SO_ORIGINAL_DST
- except AttributeError:
- # There is a missing const in the socket module... So we will add it now
- socket.SO_ORIGINAL_DST = 80
-
- def get_original_dest(sock):
- '''Gets the original destination address for connection that has been
- redirected by netfilter.'''
- # struct sockaddr_in {
- # short sin_family; // e.g. AF_INET
- # unsigned short sin_port; // e.g. htons(3490)
- # struct in_addr sin_addr; // see struct in_addr, below
- # char sin_zero[8]; // zero this if you want to
- # };
- # struct in_addr {
- # unsigned long s_addr; // load with inet_aton()
- # };
- # getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, (struct sockaddr_in *)&dstaddr, &dstlen);
-
- data = sock.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST, 16)
- _, port, a1, a2, a3, a4 = struct.unpack("!HHBBBBxxxxxxxx", data)
- address = "%d.%d.%d.%d" % (a1, a2, a3, a4)
- return address, port
+ try:
+ socket.SO_ORIGINAL_DST
+ except AttributeError:
+ # There is a missing const in the socket module... So we will add it now
+ socket.SO_ORIGINAL_DST = 80
+
+ def get_original_dest(sock):
+ '''Gets the original destination address for connection that has been
+ redirected by netfilter.'''
+ # struct sockaddr_in {
+ # short sin_family; // e.g. AF_INET
+ # unsigned short sin_port; // e.g. htons(3490)
+ # struct in_addr sin_addr; // see struct in_addr, below
+ # char sin_zero[8]; // zero this if you want to
+ # };
+ # struct in_addr {
+ # unsigned long s_addr; // load with inet_aton()
+ # };
+ # getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, (struct sockaddr_in *)&dstaddr, &dstlen);
+
+ data = sock.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST, 16)
+ _, port, a1, a2, a3, a4 = struct.unpack("!HHBBBBxxxxxxxx", data)
+ address = "%d.%d.%d.%d" % (a1, a2, a3, a4)
+ return address, port
elif sys.platform == "darwin":
- def get_original_dest(sock):
- '''Gets the original destination address for connection that has been
- redirected by ipfw.'''
- return sock.getsockname()
+ def get_original_dest(sock):
+ '''Gets the original destination address for connection that has been
+ redirected by ipfw.'''
+ return sock.getsockname()
class Proxy(asyncore.dispatcher):
- def __init__(self, arg):
- if isinstance(arg, tuple):
- asyncore.dispatcher.__init__(self)
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
- self.connect(arg)
- else:
- asyncore.dispatcher.__init__(self, arg)
- self.init()
-
- def init(self):
- self.end = False
- self.other = None
- self.buffer = ""
-
- def meet(self, other):
- self.other = other
- other.other = self
-
- def handle_error(self):
- print >>sys.stderr, "Proxy error:", traceback.format_exc()
- self.close()
-
- def handle_read(self):
- data = self.recv(8192)
- if len(data) > 0:
- self.other.buffer += data
-
- def handle_write(self):
- sent = self.send(self.buffer)
- self.buffer = self.buffer[sent:]
- if len(self.buffer) == 0 and self.end:
- self.close()
-
- def writable(self):
- return len(self.buffer) > 0
-
- def handle_close(self):
- if not self.other:
- return
- print >>sys.stderr, "Proxy closed"
- self.close()
- if len(self.other.buffer) == 0:
- self.other.close()
- self.other.end = True
- self.other = None
+ def __init__(self, arg):
+ if isinstance(arg, tuple):
+ asyncore.dispatcher.__init__(self)
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.connect(arg)
+ else:
+ asyncore.dispatcher.__init__(self, arg)
+ self.init()
+
+ def init(self):
+ self.end = False
+ self.other = None
+ self.buffer = ""
+
+ def meet(self, other):
+ self.other = other
+ other.other = self
+
+ def handle_error(self):
+ print >>sys.stderr, "Proxy error:", traceback.format_exc()
+ self.close()
+
+ def handle_read(self):
+ data = self.recv(8192)
+ if len(data) > 0:
+ self.other.buffer += data
+
+ def handle_write(self):
+ sent = self.send(self.buffer)
+ self.buffer = self.buffer[sent:]
+ if len(self.buffer) == 0 and self.end:
+ self.close()
+
+ def writable(self):
+ return len(self.buffer) > 0
+
+ def handle_close(self):
+ if not self.other:
+ return
+ print >>sys.stderr, "Proxy closed"
+ self.close()
+ if len(self.other.buffer) == 0:
+ self.other.close()
+ self.other.end = True
+ self.other = None
class ConnectProxy(asyncore.dispatcher):
- def __init__(self, sock):
- asyncore.dispatcher.__init__(self, sock)
- self.buffer = ""
-
- def handle_error(self):
- print >>sys.stderr, "ConnectProxy error:", traceback.format_exc()
- self.close()
-
- def handle_read(self):
- self.buffer += self.recv(8192)
- pos1 = self.buffer.find("\n")
- if pos1 < 0:
- return
- host = self.buffer[:pos1].strip()
- pos1 += 1
- pos2 = self.buffer[pos1:].find("\n")
- if pos2 < 0:
- return
- pos2 += pos1
- port = int(self.buffer[pos1:pos2].strip())
-
- self.buffer = self.buffer[pos2+1:]
- self.done(host, port)
-
- def handle_write(self):
- pass
-
- def handle_close(self):
- print >>sys.stderr, "Proxy closed"
- self.close()
-
- def done(self, host, port):
- print >>sys.stderr, "Forwarding connection", host, port
-
- # Create server proxy
- server = Proxy((host, port))
- server.buffer = self.buffer
-
- # Morph and connect
- self.__class__ = Proxy
- self.init()
- server.meet(self)
+ def __init__(self, sock):
+ asyncore.dispatcher.__init__(self, sock)
+ self.buffer = ""
+
+ def handle_error(self):
+ print >>sys.stderr, "ConnectProxy error:", traceback.format_exc()
+ self.close()
+
+ def handle_read(self):
+ self.buffer += self.recv(8192)
+ pos1 = self.buffer.find("\n")
+ if pos1 < 0:
+ return
+ host = self.buffer[:pos1].strip()
+ pos1 += 1
+ pos2 = self.buffer[pos1:].find("\n")
+ if pos2 < 0:
+ return
+ pos2 += pos1
+ port = int(self.buffer[pos1:pos2].strip())
+
+ self.buffer = self.buffer[pos2+1:]
+ self.done(host, port)
+
+ def handle_write(self):
+ pass
+
+ def handle_close(self):
+ print >>sys.stderr, "Proxy closed"
+ self.close()
+
+ def done(self, host, port):
+ print >>sys.stderr, "Forwarding connection", host, port
+
+ # Create server proxy
+ server = Proxy((host, port))
+ server.buffer = self.buffer
+
+ # Morph and connect
+ self.__class__ = Proxy
+ self.init()
+ server.meet(self)
class BasicForwarder(asyncore.dispatcher):
- def __init__(self, listen_port, host, port, allowed):
- asyncore.dispatcher.__init__(self)
- self.host = host
- self.port = port
- self.allowed = allowed
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
- self.set_reuse_addr()
- self.bind(("", listen_port))
- self.listen(50)
- print >>sys.stderr, "BasicForwarder bound on", listen_port
-
- def handle_error(self):
- print >>sys.stderr, "BasicForwarder error:", traceback.format_exc()
-
- def handle_accept(self):
- client_connection, source_addr = self.accept()
- if source_addr[0] not in map(socket.gethostbyname, self.allowed):
- print >>sys.stderr, "Rejected connection from", source_addr
- client_connection.close()
- return
-
- print >>sys.stderr, "Accepted connection from", source_addr
-
- # Hook the sockets up to the event loop
- client = Proxy(client_connection)
- server = Proxy((self.host, self.port))
- server.meet(client)
+ def __init__(self, listen_port, host, port, allowed):
+ asyncore.dispatcher.__init__(self)
+ self.host = host
+ self.port = port
+ self.allowed = allowed
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.set_reuse_addr()
+ self.bind(("", listen_port))
+ self.listen(50)
+ print >>sys.stderr, "BasicForwarder bound on", listen_port
+
+ def handle_error(self):
+ print >>sys.stderr, "BasicForwarder error:", traceback.format_exc()
+
+ def handle_accept(self):
+ client_connection, source_addr = self.accept()
+ if source_addr[0] not in map(socket.gethostbyname, self.allowed):
+ print >>sys.stderr, "Rejected connection from", source_addr
+ client_connection.close()
+ return
+
+ print >>sys.stderr, "Accepted connection from", source_addr
+
+ # Hook the sockets up to the event loop
+ client = Proxy(client_connection)
+ server = Proxy((self.host, self.port))
+ server.meet(client)
class Forwarder(asyncore.dispatcher):
- def __init__(self, listen_port, allowed):
- asyncore.dispatcher.__init__(self)
- self.allowed = allowed
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
- self.set_reuse_addr()
- self.bind(("", listen_port))
- self.listen(50)
- print >>sys.stderr, "Forwarder bound on", listen_port
-
- def handle_error(self):
- print >>sys.stderr, "Forwarder error:", traceback.format_exc()
-
- def handle_accept(self):
- client_connection, source_addr = self.accept()
- if source_addr[0] not in map(socket.gethostbyname, self.allowed):
- print >>sys.stderr, "Rejected connection from", source_addr
- client_connection.close()
- return
-
- print >>sys.stderr, "Accepted connection from", source_addr
- ConnectProxy(client_connection)
+ def __init__(self, listen_port, allowed):
+ asyncore.dispatcher.__init__(self)
+ self.allowed = allowed
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.set_reuse_addr()
+ self.bind(("", listen_port))
+ self.listen(50)
+ print >>sys.stderr, "Forwarder bound on", listen_port
+
+ def handle_error(self):
+ print >>sys.stderr, "Forwarder error:", traceback.format_exc()
+
+ def handle_accept(self):
+ client_connection, source_addr = self.accept()
+ if source_addr[0] not in map(socket.gethostbyname, self.allowed):
+ print >>sys.stderr, "Rejected connection from", source_addr
+ client_connection.close()
+ return
+
+ print >>sys.stderr, "Accepted connection from", source_addr
+ ConnectProxy(client_connection)
class Interceptor(asyncore.dispatcher):
- def __init__(self, listen_port, host, port):
- asyncore.dispatcher.__init__(self)
- self.host = host
- self.port = port
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
- self.set_reuse_addr()
- self.bind(("0.0.0.0", listen_port))
- self.listen(50)
- print >>sys.stderr, "Interceptor bound on", listen_port
-
- def handle_error(self):
- print >>sys.stderr, "Interceptor error!", traceback.format_exc()
-
- def handle_accept(self):
- # Get sockets
- client_connection, source_addr = self.accept()
- dest = get_original_dest(client_connection)
- print >>sys.stderr, "Accepted connection from", source_addr
-
- # Hook them up to the event loop
- client = Proxy(client_connection)
- server = Proxy((self.host, self.port))
- server.buffer += "%s\n%d\n" % dest
- server.meet(client)
+ def __init__(self, listen_port, host, port):
+ asyncore.dispatcher.__init__(self)
+ self.host = host
+ self.port = port
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.set_reuse_addr()
+ self.bind(("0.0.0.0", listen_port))
+ self.listen(50)
+ print >>sys.stderr, "Interceptor bound on", listen_port
+
+ def handle_error(self):
+ print >>sys.stderr, "Interceptor error!", traceback.format_exc()
+
+ def handle_accept(self):
+ # Get sockets
+ client_connection, source_addr = self.accept()
+ dest = get_original_dest(client_connection)
+ print >>sys.stderr, "Accepted connection from", source_addr
+
+ # Hook them up to the event loop
+ client = Proxy(client_connection)
+ server = Proxy((self.host, self.port))
+ server.buffer += "%s\n%d\n" % dest
+ server.meet(client)
def main(listen_port, host, port, mode, allowed):
- if mode == "basic":
- proxy = BasicForwarder(listen_port, host, port, allowed)
- elif mode == "proxy":
- proxy = Forwarder(listen_port, allowed)
- elif mode == "interceptor":
- proxy = Interceptor(listen_port, host, port)
- else:
- print >>sys.stderr, "Unknown mode:", mode
- return 1
- asyncore.loop()
+ if mode == "basic":
+ proxy = BasicForwarder(listen_port, host, port, allowed)
+ elif mode == "proxy":
+ proxy = Forwarder(listen_port, allowed)
+ elif mode == "interceptor":
+ proxy = Interceptor(listen_port, host, port)
+ else:
+ print >>sys.stderr, "Unknown mode:", mode
+ return 1
+ asyncore.loop()
if __name__ == "__main__":
- try:
- if sys.argv[1] == "-d":
- daemon = True
- config = sys.argv[2]
- else:
- daemon = False
- config = sys.argv[1]
- except (IndexError, ValueError):
- print >>sys.stderr, "Usage: %s [-d] config" % sys.argv[0]
- sys.exit(1)
-
- try:
- c = ConfigParser.RawConfigParser()
- c.read(config)
- except:
- print >>sys.stderr, "Error parsing config!"
- sys.exit(1)
-
- def guard(func, message):
- try:
- return func()
- except:
- print >>sys.stderr, "Error:", message
- raise
- sys.exit(1)
-
- mode = guard(lambda:c.get("proxy", "mode").lower(),
- "mode is a required field")
-
- listen_port = guard(lambda:c.getint("proxy", "listen_port"),
- "listen_port is a required field")
-
- if mode in ["basic", "interceptor"]:
- text = "%%s is a required field for mode=%s" % mode
- host = guard(lambda:c.get("proxy", "host"), text % "host")
- port = guard(lambda:c.getint("proxy", "port"), text % "port")
- else:
- host = None
- port = None
-
- if mode in ["basic", "proxy"]:
- allowed = guard(lambda:c.items("allowed"),
- "[allowed] section is required for mode=%s" % mode)
- allowed = [h for _,h in c.items("allowed")]
- else:
- allowed = None
-
-
- if not daemon:
- try:
- main(listen_port, host, port, mode, allowed)
- except KeyboardInterrupt:
- print
- else:
- os.close(0)
- os.close(1)
- os.close(2)
- os.open("/dev/null", os.O_RDONLY)
- os.open("/dev/null", os.O_RDWR)
- os.dup(1)
-
- if os.fork() == 0:
- # We are the child
- try:
- sys.exit(main(listen_port, host, port, mode, allowed))
- except KeyboardInterrupt:
- print
- sys.exit(0)
+ try:
+ if sys.argv[1] == "-d":
+ daemon = True
+ config = sys.argv[2]
+ else:
+ daemon = False
+ config = sys.argv[1]
+ except (IndexError, ValueError):
+ print >>sys.stderr, "Usage: %s [-d] config" % sys.argv[0]
+ sys.exit(1)
+
+ try:
+ c = ConfigParser.RawConfigParser()
+ c.read(config)
+ except:
+ print >>sys.stderr, "Error parsing config!"
+ sys.exit(1)
+
+ def guard(func, message):
+ try:
+ return func()
+ except:
+ print >>sys.stderr, "Error:", message
+ raise
+ sys.exit(1)
+
+ mode = guard(lambda:c.get("proxy", "mode").lower(),
+ "mode is a required field")
+
+ listen_port = guard(lambda:c.getint("proxy", "listen_port"),
+ "listen_port is a required field")
+
+ if mode in ["basic", "interceptor"]:
+ text = "%%s is a required field for mode=%s" % mode
+ host = guard(lambda:c.get("proxy", "host"), text % "host")
+ port = guard(lambda:c.getint("proxy", "port"), text % "port")
+ else:
+ host = None
+ port = None
+
+ if mode in ["basic", "proxy"]:
+ allowed = guard(lambda:c.items("allowed"),
+ "[allowed] section is required for mode=%s" % mode)
+ allowed = [h for _,h in c.items("allowed")]
+ else:
+ allowed = None
+
+
+ if not daemon:
+ try:
+ main(listen_port, host, port, mode, allowed)
+ except KeyboardInterrupt:
+ print
+ else:
+ os.close(0)
+ os.close(1)
+ os.close(2)
+ os.open("/dev/null", os.O_RDONLY)
+ os.open("/dev/null", os.O_RDWR)
+ os.dup(1)
+
+ if os.fork() == 0:
+ # We are the child
+ try:
+ sys.exit(main(listen_port, host, port, mode, allowed))
+ except KeyboardInterrupt:
+ print
+ sys.exit(0)
-#!/usr/bin/env python
+#!/usr/bin/python2
# Copyright 2007 James Bunton <jamesbunton@fastmail.fm>
# Licensed for distribution under the GPL version 2, check COPYING for details
# Decodes a password taken from a Psi config.xml file
import sys
def decodePassword(passwd, key):
- if not key:
- return passwd
-
- result = ""
- n1 = n2 = 0
- while n1 < len(passwd):
- x = 0
- if n1 + 4 > len(passwd):
- break
- x += int(passwd[n1+0], 16) * 4096
- x += int(passwd[n1+1], 16) * 256
- x += int(passwd[n1+2], 16) * 16
- x += int(passwd[n1+3], 16) * 1
- result += chr(x ^ ord(key[n2]))
- n1 += 4
- n2 += 1
- if n2 >= len(key):
- n2 = 0
-
- return result
+ if not key:
+ return passwd
+
+ result = ""
+ n1 = n2 = 0
+ while n1 < len(passwd):
+ x = 0
+ if n1 + 4 > len(passwd):
+ break
+ x += int(passwd[n1+0], 16) * 4096
+ x += int(passwd[n1+1], 16) * 256
+ x += int(passwd[n1+2], 16) * 16
+ x += int(passwd[n1+3], 16) * 1
+ result += chr(x ^ ord(key[n2]))
+ n1 += 4
+ n2 += 1
+ if n2 >= len(key):
+ n2 = 0
+
+ return result
if __name__ == "__main__":
- try:
- passwd = sys.argv[1]
- key = sys.argv[2]
- except:
- print >> sys.stderr, "Usage: %s passwd jid" % sys.argv[0]
- sys.exit(1)
- print decodePassword(passwd, key)
+ try:
+ passwd = sys.argv[1]
+ key = sys.argv[2]
+ except:
+ print >> sys.stderr, "Usage: %s passwd jid" % sys.argv[0]
+ sys.exit(1)
+ print decodePassword(passwd, key)
# Print status of classes
if [ "$1" = "status" ]; then
- tc -s qdisc ls dev ${IFACE}
- tc -s class ls dev ${IFACE}
- exit
+ tc -s qdisc ls dev ${IFACE}
+ tc -s class ls dev ${IFACE}
+ exit
fi
set -x
tc qdisc del dev ${IFACE} ingress 2> /dev/null > /dev/null
if [ "$1" = "stop" ]; then
- exit
+ exit
fi
cd /
# install root HTB, point default traffic to NORM_TRAFFIC
tc qdisc add dev ${IFACE} \
- root handle ${ROOT}:0 \
- htb default ${NORM_TRAFFIC}
+ root handle ${ROOT}:0 \
+ htb default ${NORM_TRAFFIC}
# LIMIT class shapes everything at $UPLINK_RATE speed
# this prevents huge queues in the DSL modem which destroy latency
tc class add dev ${IFACE} \
- parent ${ROOT}:0 classid ${ROOT}:${LIMIT} \
- htb rate ${UPLINK_RATE}Kbit ceil ${UPLINK_RATE}Kbit
+ parent ${ROOT}:0 classid ${ROOT}:${LIMIT} \
+ htb rate ${UPLINK_RATE}Kbit ceil ${UPLINK_RATE}Kbit
# VoIP traffic class gets guaranteed bandwidth
tc class add dev ${IFACE} \
- parent ${ROOT}:${LIMIT} classid ${ROOT}:${VOIP_TRAFFIC} \
- htb rate ${VOIP_RATE}Kbit ceil ${UPLINK_RATE}Kbit prio 0
+ parent ${ROOT}:${LIMIT} classid ${ROOT}:${VOIP_TRAFFIC} \
+ htb rate ${VOIP_RATE}Kbit ceil ${UPLINK_RATE}Kbit prio 0
# High priority traffic
tc class add dev ${IFACE} \
- parent ${ROOT}:${LIMIT} classid ${ROOT}:${HIGH_TRAFFIC} \
- htb rate ${HIGH_RATE}Kbit ceil ${UPLINK_RATE}Kbit prio 1
+ parent ${ROOT}:${LIMIT} classid ${ROOT}:${HIGH_TRAFFIC} \
+ htb rate ${HIGH_RATE}Kbit ceil ${UPLINK_RATE}Kbit prio 1
# Normal priority traffic
tc class add dev ${IFACE} \
- parent ${ROOT}:${LIMIT} classid ${ROOT}:${NORM_TRAFFIC} \
- htb rate ${NORM_RATE}Kbit ceil ${UPLINK_RATE}Kbit prio 2
+ parent ${ROOT}:${LIMIT} classid ${ROOT}:${NORM_TRAFFIC} \
+ htb rate ${NORM_RATE}Kbit ceil ${UPLINK_RATE}Kbit prio 2
# Bulk traffic gets little default allowance
tc class add dev ${IFACE} \
- parent ${ROOT}:${LIMIT} classid ${ROOT}:${BULK_TRAFFIC} \
- htb rate ${BULK_RATE}Kbit ceil ${UPLINK_RATE}Kbit prio 3
+ parent ${ROOT}:${LIMIT} classid ${ROOT}:${BULK_TRAFFIC} \
+ htb rate ${BULK_RATE}Kbit ceil ${UPLINK_RATE}Kbit prio 3
# Stochastic Fairness
tc qdisc add dev ${IFACE} \
- parent ${ROOT}:${HIGH_TRAFFIC} handle ${HIGH_TRAFFIC}:0 \
- sfq perturb 10
+ parent ${ROOT}:${HIGH_TRAFFIC} handle ${HIGH_TRAFFIC}:0 \
+ sfq perturb 10
tc qdisc add dev ${IFACE} \
- parent ${ROOT}:${NORM_TRAFFIC} handle ${NORM_TRAFFIC}:0 \
- sfq perturb 10
+ parent ${ROOT}:${NORM_TRAFFIC} handle ${NORM_TRAFFIC}:0 \
+ sfq perturb 10
tc qdisc add dev ${IFACE} \
- parent ${ROOT}:${BULK_TRAFFIC} handle ${BULK_TRAFFIC}:0 \
- sfq perturb 10
+ parent ${ROOT}:${BULK_TRAFFIC} handle ${BULK_TRAFFIC}:0 \
+ sfq perturb 10
# Match VoIP traffic as highest priority
tc filter add dev ${IFACE} \
- parent ${ROOT}:0 protocol ip prio 10 u32 \
- match ip dst ${VOIP_HOST} flowid ${ROOT}:${VOIP_TRAFFIC}
+ parent ${ROOT}:0 protocol ip prio 10 u32 \
+ match ip dst ${VOIP_HOST} flowid ${ROOT}:${VOIP_TRAFFIC}
# ICMP in the HIGH_TRAFFIC class
tc filter add dev ${IFACE} \
- parent ${ROOT}:0 protocol ip prio 10 u32 \
- match ip protocol 1 0xff flowid ${ROOT}:${HIGH_TRAFFIC}
+ parent ${ROOT}:0 protocol ip prio 10 u32 \
+ match ip protocol 1 0xff flowid ${ROOT}:${HIGH_TRAFFIC}
# To speed up downloads while an upload is going on, ACK is HIGH_TRAFFIC
tc filter add dev ${IFACE} \
- parent ${ROOT}:0 protocol ip prio 10 u32 \
- match ip protocol 6 0xff \
- match u8 0x05 0x0f at 0 \
- match u16 0x0000 0xffc0 at 2 \
- match u8 0x10 0xff at 33 \
- flowid ${ROOT}:${HIGH_TRAFFIC}
+ parent ${ROOT}:0 protocol ip prio 10 u32 \
+ match ip protocol 6 0xff \
+ match u8 0x05 0x0f at 0 \
+ match u16 0x0000 0xffc0 at 2 \
+ match u8 0x10 0xff at 33 \
+ flowid ${ROOT}:${HIGH_TRAFFIC}
# TOS Minimum-Delay (eg ssh but not scp) in HIGH_TRAFFIC
tc filter add dev ${IFACE} \
- parent ${ROOT}:0 protocol ip prio 10 u32 \
- match ip tos 0x10 0xff flowid ${ROOT}:${HIGH_TRAFFIC}
+ parent ${ROOT}:0 protocol ip prio 10 u32 \
+ match ip tos 0x10 0xff flowid ${ROOT}:${HIGH_TRAFFIC}
# TOS Maximise-Throughput (eg rtorrent) in BULK_TRAFFIC
tc filter add dev ${IFACE} \
- parent ${ROOT}:0 protocol ip prio 10 u32 \
- match ip tos 0x08 0xff flowid ${ROOT}:${BULK_TRAFFIC}
+ parent ${ROOT}:0 protocol ip prio 10 u32 \
+ match ip tos 0x08 0xff flowid ${ROOT}:${BULK_TRAFFIC}
-#!/usr/bin/env python
+#!/usr/bin/python2
import fcntl
import os
import time
if not sys.platform.startswith("linux"):
- print >>sys.stderr, "Sorry, this tool requires Linux"
- sys.exit(1)
+ print >>sys.stderr, "Sorry, this tool requires Linux"
+ sys.exit(1)
try:
- search_usb_id = sys.argv[1].lower()
+ search_usb_id = sys.argv[1].lower()
except IndexError:
- print >>sys.stderr, "Usage: %s vendorid:devid" % sys.argv[0]
- print >>sys.stderr, "\nThis tool will reset all USB devices with the given ID (eg 1f4d:a803)"
- sys.exit(1)
+ print >>sys.stderr, "Usage: %s vendorid:devid" % sys.argv[0]
+ print >>sys.stderr, "\nThis tool will reset all USB devices with the given ID (eg 1f4d:a803)"
+ sys.exit(1)
USBDEVFS_RESET = 21780
p = subprocess.Popen(["lsusb"], stdout=subprocess.PIPE)
for line in p.stdout:
- line = line.split()
- usb_id = line[5].lower()
- if usb_id != search_usb_id:
- continue
- bus = line[1]
- dev = line[3].replace(":", "")
-
- filename = "/dev/bus/usb/%s/%s" % (bus, dev)
- print "Resetting", filename, "...",
- sys.stdout.flush()
- fd = os.open(filename, os.O_WRONLY)
- ret = fcntl.ioctl(fd, USBDEVFS_RESET, 0)
- if ret < 0:
- print >>sys.stderr, "\nError in ioctl:", ret
- sys.exit(1)
- os.close(fd)
- time.sleep(1)
- print "done"
+ line = line.split()
+ usb_id = line[5].lower()
+ if usb_id != search_usb_id:
+ continue
+ bus = line[1]
+ dev = line[3].replace(":", "")
+
+ filename = "/dev/bus/usb/%s/%s" % (bus, dev)
+ print "Resetting", filename, "...",
+ sys.stdout.flush()
+ fd = os.open(filename, os.O_WRONLY)
+ ret = fcntl.ioctl(fd, USBDEVFS_RESET, 0)
+ if ret < 0:
+ print >>sys.stderr, "\nError in ioctl:", ret
+ sys.exit(1)
+ os.close(fd)
+ time.sleep(1)
+ print "done"