Skip to content

Instantly share code, notes, and snippets.

@juanplopes juanplopes/mvngithub.py
Last active May 19, 2018

Embed
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':'http://maven.apache.org/SETTINGS/1.0.0'}
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('api.github.com', 443)
body = json.dumps({'note':'{} {} {}'.format(socket.gethostname(), repokey, str(datetime.datetime.now())), 'scopes': ['repo']})
headers = {'User-Agent': 'repokey.py'}
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
print resp.read()
return None
else:
respjson = json.loads(resp.read())
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)
else:
print filename, 'does not exist. Creating new.'
tree = ET.ElementTree(ET.fromstring(
"""
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
</servers>
</settings>
"""))
root = tree.getroot()
xml = ET.fromstring(
"""
<server xmlns="http://maven.apache.org/SETTINGS/1.0.0">
<id>{}</id>
<configuration>
<httpHeaders>
<property>
<name>Authorization</name>
<value>Basic {}</value>
</property>
</httpHeaders>
</configuration>
</server>
""".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)
servers.remove(server)
servers.append(xml)
backup = filename + '.bkp'
print 'Backing up', backup
if os.path.exists(backup):
os.remove(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')
else:
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.