Created
September 11, 2016 23:29
-
-
Save binarytemple/4403f9ce3ea21180396140b1b9a3c530 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import getopt | |
import sys | |
import keyring | |
import getpass | |
""" | |
Password wrapper, get and store passwords to system keyring | |
License: Apache Software License | |
Author: Bryan Hunt (binarytemple) | |
""" | |
def helpmsg(): | |
msg="%s \n" % ( sys.argv[0] ) | |
msg+=""" | |
-h --help (this message) | |
-g --get | |
or | |
-s --set | |
-a <account> --account=<account> | |
-u <user> --user=<user> | |
""" | |
print msg | |
def parse(args_array): | |
""" | |
>>> parse('--set --account=foo --user=bar'.split()) | |
([('--set', ''), ('--account', 'foo'), ('--user', 'bar')], []) | |
>>> parse('--get --account=foo --user=bar'.split()) | |
([('--get', ''), ('--account', 'foo'), ('--user', 'bar')], []) | |
>>> parse('--help'.split()) | |
([('--help', '')], []) | |
>>> parse('-h'.split()) | |
([('-h', '')], []) | |
""" | |
import getopt | |
return getopt.getopt(args_array, ':hgsa:u:',[ "help","get","set","account=","user="]) | |
def main(): | |
try: | |
opts, args = parse(sys.argv[1:]) | |
except getopt.error, msg: | |
print msg | |
helpmsg() | |
sys.exit(1) | |
account="" | |
user="" | |
action="" | |
# process options | |
for o, a in opts: | |
if o in ("-h", "--help"): | |
helpmsg() | |
sys.exit(0) | |
if o in "-g" or o == "--get": | |
action = "get" | |
if o in "-s" or o == "--set": | |
action = "set" | |
if o in "-a" or o == "--account": | |
account = a | |
if o in "-u" or o == "--user": | |
user = a | |
if action == "" or user == "" or account == "" or len(opts) == 0: | |
helpmsg() | |
sys.exit(1) | |
#print "%s, %s, %s %s" % ( action, user, account, len(opts) ) | |
if action == "get": | |
password=keyring.get_password(account,user) | |
if password == None: | |
print "Password not found" | |
sys.exit(1) | |
else: | |
print password | |
elif action == "set": | |
print "Please enter the password" | |
password=getpass.getpass() | |
if password == None or password == "": | |
print "Empty password provided, password not set" | |
sys.exit(1) | |
keyring.set_password(account,user,password) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also : http://lzone.de/blog/Access%20GnomeKeyring%20with%20Python%20GIR