Skip to content

Instantly share code, notes, and snippets.

@juanplopes juanplopes/
Last active May 19, 2018

What would you like to do?
Python 2 script that asks github for new application token and saves it on .m2/settings.xml
#!/usr/bin/env python
import httplib, getpass, base64, json, datetime, sys, socket, xml.etree.ElementTree as ET, os.path as path, os
NS = {'n':''}
DEFAULT_REPO_KEY = 'your-repo-key'
def make_auth(username, password):
return base64.b64encode('{}:{}'.format(username, password))
def make_token(repokey, username, password, token2fa):
print 'Generating new token for', username
auth = make_auth(username, password)
conn = httplib.HTTPSConnection('', 443)
body = json.dumps({'note':'{} {} {}'.format(socket.gethostname(), repokey, str(, 'scopes': ['repo']})
headers = {'User-Agent': ''}
if username:
print 'Adding basic auth info'
headers['Authorization'] = 'Basic {}'.format(auth)
if token2fa:
print 'Adding 2FA info'
headers['X-GitHub-OTP'] = token2fa
conn.request('POST', '/authorizations', body, headers)
resp = conn.getresponse()
if resp.status/100 != 2:
print resp.status
print resp.reason
print resp.msg
return None
respjson = json.loads(
print 'Created token', respjson['note']
return respjson['token']
def add_token(filename, repokey, username, password):
auth = make_auth(username, password)
if os.path.exists(filename):
tree = ET.parse(filename)
print filename, 'does not exist. Creating new.'
tree = ET.ElementTree(ET.fromstring(
<settings xmlns="" xmlns:xsi="" xsi:schemaLocation="">
root = tree.getroot()
xml = ET.fromstring(
<server xmlns="">
<value>Basic {}</value>
""".format(repokey, auth))
servers = root.find('n:servers', namespaces=NS)
for server in servers.findall('n:server[n:id="{}"]'.format(repokey), namespaces=NS):
print 'Removing existing {} config'.format(repokey)
backup = filename + '.bkp'
print 'Backing up', backup
if os.path.exists(backup):
if os.path.exists(filename):
os.rename(filename, backup)
print 'Writing', filename
tree.write(filename, default_namespace=NS['n'])
def def_input(prompt, default):
return raw_input(prompt.format(default)) or default
username = raw_input('Github username: ')
password = getpass.getpass('Password: ')
generate = raw_input('Generate token with supplied password [Y/n]: ')
if generate.lower() != "n":
token2fa = raw_input('2-factor auth token (leave blank for none): ')
repokey = def_input('Maven repository key [{}]: ', DEFAULT_REPO_KEY)
username = make_token(repokey, username, password, token2fa)
password = ''
username or sys.exit('No token was created')
repokey = def_input('Maven repository key [{}]: ', DEFAULT_REPO_KEY)
filename = def_input('M2 settings [{}]: ', path.join(path.expanduser("~"), '.m2/settings.xml'))
print 'Writing authorization...'
add_token(filename, repokey, username, password)
print 'DONE.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.