Skip to content

Instantly share code, notes, and snippets.

@ravishi
Last active October 10, 2015 19:37
Show Gist options
  • Save ravishi/3740485 to your computer and use it in GitHub Desktop.
Save ravishi/3740485 to your computer and use it in GitHub Desktop.
Adds a PPA by using urllib to get it's key. Useful when you are behind a restrictive proxy (I think I created it because apt-add-repository was having some problems with a proxy configuration...)
#!/usr/bin/env python
from __future__ import unicode_literals
from __future__ import print_function
import contextlib
import subprocess
import tempfile
import urllib2
import os.path
import bs4
class InvalidPPA(Exception):
pass
def get_key(skterm):
keyserver = 'http://keyserver.ubuntu.com:11371'
keysearch_url = keyserver + '/pks/lookup?search=0x{0}&op=vindex'.format(skterm)
with contextlib.closing(urllib2.urlopen(keysearch_url)) as page:
soup = bs4.BeautifulSoup(page.read())
key_url = soup.select('body pre a')[0].attrs.get('href')
if not key_url.startswith('http'):
key_url = keyserver + key_url
with contextlib.closing(urllib2.urlopen(key_url)) as page:
soup = bs4.BeautifulSoup(page.read())
key = soup.select('body pre')[0].text.strip()
return key
def get(name):
if not name.startswith('ppa:'):
raise InvalidPPA(name)
components = name[4:].split('/')
if len(components) != 2:
raise InvalidPPA(name)
url = 'https://launchpad.net/~{0}/+archive/{1}'.format(*components)
with contextlib.closing(urllib2.urlopen(url)) as page:
soup = bs4.BeautifulSoup(page.read())
sk = soup.select('#signing-key code')[0].text.strip()
src = soup.select('#sources-list-entries')[0].text.strip()
skterm = sk.split('/')[-1]
return dict(name=name, key=get_key(skterm), src=src)
def add(ppa):
release_file = '/etc/lsb-release'
upstream_release_file = '/etc/upstream-release/lsb-release'
if os.path.isfile(upstream_release_file):
release_file = upstream_release_file
with open(release_file) as lsb:
relinfo = dict(line.strip().split('=') for line in lsb.readlines())
version = relinfo['DISTRIB_CODENAME']
srcfname = '-'.join(tuple(ppa['name'][4:].split('/')) + (version,)) + '.list'
fd, path = tempfile.mkstemp(text=True)
with contextlib.closing(os.fdopen(fd, 'w')) as keyfile:
keyfile.write(ppa['key'])
keyfile.flush()
if subprocess.call(['apt-key', 'add', path]):
raise RuntimeError('failed to add the key')
with open(os.path.join('/etc/apt/sources.list.d', srcfname), 'w') as srcfile:
srcfile.write(ppa['src'].replace('YOUR_UBUNTU_VERSION_HERE', version))
def main(argv):
add(get(argv[1]))
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv) or 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment