Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Script em Python para gerar um ~/.m2/settings.xml com token de acesso a repositório no GitHub.
#!/usr/bin/env python
import httplib, getpass, base64, json, datetime, sys, xml.etree.ElementTree as ET, os.path as path, os
KEY = 'your-private-repo'
NS = {'n':''}
def make_auth(username, password):
return base64.b64encode('{}:{}'.format(username, password))
def make_token(repokey, username, password):
print 'Generating new token for', username
auth = make_auth(username, password)
conn = httplib.HTTPSConnection('', 443)
body = json.dumps({'note':'{} {}'.format(repokey, str(, 'scopes': ['repo']})
headers = {'Authorization': 'Basic {}'.format(auth)}
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: ')
filename = def_input('M2 settings [{}]: ', path.join(path.expanduser("~"), '.m2/settings.xml'))
repokey = def_input('Maven repository key [{}]: ', KEY)
generate = raw_input('Generate token with supplied password [Y/n]: ')
if generate.lower() != "n":
username = make_token(repokey, username, password)
password = ''
username or sys.exit('No token was created')
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