Skip to content

Instantly share code, notes, and snippets.

@flexiondotorg
Created October 10, 2017 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flexiondotorg/84c3f137d70f4e21ea46419833c0aff4 to your computer and use it in GitHub Desktop.
Save flexiondotorg/84c3f137d70f4e21ea46419833c0aff4 to your computer and use it in GitHub Desktop.
Python example of using snapd-glib to authenticate, install and remove snaps.
#!/usr/bin/python3
#http://people.ubuntu.com/~robert-ancell/snapd-glib/reference/index.html
import getpass
import gi
import json
import os
import sys
gi.require_version ('Snapd', '1')
from gi.repository import Snapd
def progress_snap_cb (client, change, _, user_data):
# Interate over tasks to determine the aggregate tasks for completion.
total = 0
done = 0
for task in change.get_tasks():
total += task.get_progress_total()
done += task.get_progress_done()
percent = round((done/total)*100)
print(percent)
def load_auth_data():
if os.path.exists(os.path.join(os.path.expanduser('~'),'.deleteme')):
with open(os.path.join(os.path.expanduser('~'),'.deleteme')) as stream:
auth_data = json.load(stream)
macaroon = auth_data['macaroon']
discharges = auth_data['discharges']
auth_data = Snapd.AuthData.new(macaroon, discharges)
print(auth_data)
else:
auth_data = None
return auth_data
def save_auth_data(auth_data):
macaroon = Snapd.AuthData.get_macaroon(auth_data)
discharges = Snapd.AuthData.get_discharges(auth_data)
data = {'macaroon': macaroon,
'discharges': discharges}
f = open(os.path.join(os.path.expanduser('~'),'.deleteme'), "w+")
f.write(json.dumps(data))
f.close()
def snap_login():
username = input('Username:')
password = getpass.getpass(prompt='Password:')
try:
auth_data = Snapd.login_sync(username, password, None)
except Exception as e:
if e.domain == 'snapd-error-quark' and e.code == Snapd.Error.TWO_FACTOR_REQUIRED:
otp = input('OTP:')
try:
auth_data = Snapd.login_sync(username, password, otp)
except:
return False
else:
return False
client.set_auth_data(auth_data)
save_auth_data(auth_data)
return True
def snap_install(snapname):
#print("Installing {}").format(snapname)
client.install_sync(snapname,
None, # channel
progress_snap_cb, (None,),
None) # cancellable
def snap_remove(snapname):gt check
#print("Removing {}").format(snapname)
client.remove_sync(snapname,
progress_snap_cb, (None,),
None) # cancellable
def is_installed(snapname):
try:
snapinfo = client.list_one_sync(snapname)
except Exception as e:
return False
else:
return True
client = Snapd.Client()
client.connect_sync()
auth_data = load_auth_data()
if auth_data:
client.set_auth_data(auth_data)
else:
snap_login()
if not is_installed('pin-town'):
snap_install('pin-town')
if is_installed('pin-town'):
snap_remove('pin-town')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment