def test_successive_ftp(): console.hud_alert('mac') user = '******' pwd = keychain.get_password('FTPiMac', user) try: FTP = FTP('iMac.local') #connect FTP.encoding = 'utf-8' FTP.login(user, pwd) print('mac') print(list(FTP.mlsd('Google Drive/Budget'))) FTP.quit() del FTP except: console.alert('Mac not accessible', '', 'ok', hide_cancel_button=True) console.hud_alert('adrive') user = '******' pwd = keychain.get_password('ADrive', user) try: FTP = FTP('ftp.adrive.com') #connect FTP.encoding = 'utf-8' FTP.login(user, pwd) print('adrive') print(list(FTP.mlsd('Google Drive/Budget'))) FTP.quit() del FTP except: console.alert('ADrive not accessible', '', 'ok', hide_cancel_button=True)
def get_api_key(): api_key = keychain.get_password('wunderground', 'api') If api_key == None: api_key = console.input_alert('No API Key', 'You must register for a free api key at https://www.wunderground.com/weather/api and enter it here:', '', 'Ok', hide_cancel_button = False) If api_key <> '': api_key = keychain.set_password('wunderground', 'api', api_key) api_key = keychain.get_password('wunderground', 'api')
def get_credentials() -> typing.Tuple[str, str]: """Get Pushover user and api_token.""" try: user = os.environ["PUSHOVER_USER"] api_token = os.environ["PUSHOVER_API_TOKEN"] except KeyError: user = keychain.get_password("pushover", "user") api_token = keychain.get_password("pushover", "api_token") return user, api_token
def get_api_key(): api_key = keychain.get_password('moviedb', 'api') If api_key == None: api_key = console.input_alert('No API Key', 'You must generate an api key at https://www.themoviedb.org and enter it here:', '', 'Ok', hide_cancel_button = False) If api_key <> '': api_key = keychain.set_password('moviedb', 'api', api_key) api_key = keychain.get_password('moviedb', 'api')
def get_services(self, blob=None): if blob and os.path.isfile(blob): import lastpass email = keychain.get_password('lastpass_email', 'lastpass') password = keychain.get_password('lastpass_master', 'lastpass') or '' email, password = console.login_alert('LastPass login', '', email, password) vault = lastpass.Vault.open_local(blob, email, password) return [(x.name, x.username, x.password) for x in vault.accounts] else: return keychain.get_services()
def perform_backup(quiet=True): try: from urllib2 import urlopen except: try: from urllib.request import urlopen except: pass try: urlopen('http://s3.amazonaws.com') except: if quiet: return else: sys.exit('ERROR: Unable to connect to s3.amazonaws.com') doc_path = os.path.expanduser('~/Documents') os.chdir(doc_path) backup_path = os.path.join(doc_path, 'Backup.zip') if os.path.exists(backup_path): os.remove(backup_path) print('Creating backup archive...') shutil.make_archive(os.path.join(tempfile.gettempdir(), 'Backup'), 'zip') shutil.move(os.path.join(tempfile.gettempdir(), 'Backup.zip'), backup_path) print('Backup archive created, uploading to S3 ...') date_text = time.strftime('%Y-%b-%d') time_text = time.strftime('%I-%M-%S-%p') info_dict_version_key = 'CFBundleShortVersionString' main_bundle = NSBundle.mainBundle() app_version = str( main_bundle.objectForInfoDictionaryKey_(info_dict_version_key))[0] AWS_ACCESS_KEY_ID = keychain.get_password('aws', 'AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = keychain.get_password('aws', 'AWS_SECRET_ACCESS_KEY') bucket_name = 'lukaskollmer' def percent_cb(complete, total): reprint('{}'.format(round(float(complete) / float(total) * 100, 2))) s3 = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = s3.get_bucket(bucket_name) filename = 'Backup-{}.zip'.format(time_text) k = Key(bucket) k.storage_class = 'REDUCED_REDUNDANCY' k.key = '/Backup/Pythonista{}/{}/{}'.format(app_version, date_text, filename) print('0.0 %') k.set_contents_from_filename('Backup.zip', cb=percent_cb, num_cb=10) print('Successfully uploaded') os.remove(backup_path)
def load_credentials(): username = keychain.get_password(get_username_service(), 'username') password = None if username is not None: password = keychain.get_password(get_password_service(), username) if username is None: username = '' if password is None: password = '' return username, password
def perform_backup(quiet=True): try: from urllib2 import urlopen except: try: from urllib.request import urlopen except: pass try: urlopen('http://s3.amazonaws.com') except: if quiet: return else: sys.exit('ERROR: Unable to connect to s3.amazonaws.com') doc_path = os.path.expanduser('~/Documents') os.chdir(doc_path) backup_path = os.path.join(doc_path, 'Backup.zip') if os.path.exists(backup_path): os.remove(backup_path) print('Creating backup archive...') shutil.make_archive(os.path.join(tempfile.gettempdir(), 'Backup'), 'zip') shutil.move(os.path.join(tempfile.gettempdir(), 'Backup.zip'), backup_path) print('Backup archive created, uploading to S3 ...') date_text = time.strftime('%Y-%b-%d') time_text = time.strftime('%I-%M-%S-%p') info_dict_version_key = 'CFBundleShortVersionString' main_bundle = NSBundle.mainBundle() app_version = str(main_bundle.objectForInfoDictionaryKey_(info_dict_version_key))[0] AWS_ACCESS_KEY_ID = keychain.get_password('aws', 'AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = keychain.get_password('aws', 'AWS_SECRET_ACCESS_KEY') bucket_name = 'lukaskollmer' def percent_cb(complete, total): reprint('{}'.format(round(float(complete) / float(total) * 100, 2))) s3 = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = s3.get_bucket(bucket_name) filename = 'Backup-{}.zip'.format(time_text) k = Key(bucket) k.storage_class = 'REDUCED_REDUNDANCY' k.key = '/Backup/Pythonista{}/{}/{}'.format(app_version, date_text, filename) print('0.0 %') k.set_contents_from_filename('Backup.zip', cb=percent_cb, num_cb=10) print('Successfully uploaded') os.remove(backup_path)
def __init__(self): config = keychain.get_password('Movie Diary', 'Config') if config == None: moviedb_api = keychain.get_password('MovieDB', 'API') airtable_api = keychain.get_password('Airtable', 'API') airtable_db = keychain.get_password('Airtable', 'Movie Diary') airtable_table = keychain.get_password('Airtable', 'Movie Diary Table') if airtable_api == None or airtable_db == None or airtable_table == None: airtable_api, airtable_db, airtable_table = self.getairtable(airtable_api, airtable_db, airtable_table) config = dialogs.form_dialog(title='Movie Diary Configuration', sections=[('MovieDB', [{'type': 'text', 'key': 'moviedb_api', 'value': moviedb_api if moviedb_api is not None else '84cef43ccf02b1ba6093c9694ed671c9', 'title': 'MovieDB API Token'}]), ('Airtable', [{'type': 'text', 'key': 'airtable_api', 'value': airtable_api, 'title': 'Airtable API Key'}, {'type': 'text', 'key': 'airtable_db', 'value': airtable_db, 'title': 'Airtable database ID'}, {'type': 'text', 'key': 'airtable_table', 'value': airtable_table if airtable_table is not None else 'Table 1', 'title': 'Airtable table name'}]), ('Custom', [{'type': 'switch', 'key': 'set_date_manually', 'value': False, 'title': 'Set date manually'}, {'type': 'switch', 'key': 'add_time_to_date', 'value': False, 'title': 'Add time to date'}]),('Extra Fields', [{'type': 'switch', 'key': 'directors_field', 'value': True, 'title': 'Directors'}, {'type': 'switch', 'key': 'genres_field', 'value': False, 'title': 'Genres'}, {'type': 'switch', 'key': 'runtime_field', 'value': False, 'title': 'Runtime'}, {'type': 'switch', 'key': 'cast_field', 'value': False, 'title': 'Cast'}, {'type': 'switch', 'key': 'imdb_field', 'value': False, 'title': 'IMDB URL'}]),('Fields', [{'type':'text', 'key': 'title_field_name', 'value': 'Title', 'title': 'Title'}, {'type':'text', 'key': 'overview_field_name', 'value': 'Overview', 'title': 'Overview'}, {'type':'text', 'key': 'rating_field_name', 'value': 'Rating', 'title': 'Rating'}, {'type':'text', 'key': 'date_field_name', 'value': 'Date', 'title': 'Date'}, {'type':'text', 'key': 'directors_field_name', 'value': 'Directors', 'title': 'Directors'}, {'type':'text', 'key': 'poster_field_name', 'value': 'Poster', 'title': 'Poster'}, {'type':'text', 'key': 'year_field_name', 'value': 'Year', 'title': 'Year'}, {'type':'text', 'key': 'genres_field_name', 'value': 'Genres', 'title': 'Genres'}, {'type':'text', 'key': 'cast_field_name', 'value': 'Cast', 'title': 'Cast'}, {'type':'text', 'key': 'runtime_field_name', 'value': 'Runtime', 'title': 'Runtime'}, {'type':'text', 'key': 'imdb_field_name', 'value': 'IMDB', 'title': 'IMDB URL'}])]) if config == None: raise MissingConfigError('You must setup and confirm the Movie Diary configuration before continuing.') else: config['moviedb_api'] = self.validate_config(config['moviedb_api'], 'Insert your TMDB API key', 'You need a valid MovieDB API key', '84cef43ccf02b1ba6093c9694ed671c9') config['airtable_api'] = self.validate_config(config['airtable_api'], 'Insert your Airtable API key', 'You need a valid Airtable API key') config['airtable_db'] = self.validate_config(config['airtable_db'], 'Insert your Airtable database ID', 'You need the ID of your database') config['airtable_table'] = self.validate_config(config['airtable_table'], 'Insert the name of yout Airtable table', 'You must insert the name of the table in your database.', 'Table 1', True) keychain.set_password('Movie Diary', 'Config', cPickle.dumps(config)) else: config = cPickle.loads(config) self.moviedb_api = config.get('moviedb_api', '') self.airtable_api = config.get('airtable_api', '') self.airtable_db = config.get('airtable_db', '') self.airtable_table = config.get('airtable_table', '') self.set_date_manually = config.get('set_date_manually', '') self.add_time_to_date = config.get('add_time_to_date', '') self.directors_field = config.get('directors_field', '') self.genres_field = config.get('genres_field', '') self.runtime_field = config.get('runtime_field', '') self.cast_field = config.get('cast_field', '') self.imdb_field = config.get('imdb_field', '') self.title_field_name = config.get('title_field_name', 'Title') self.overview_field_name = config.get('overview_field_name', 'Overview') self.rating_field_name = config.get('rating_field_name', 'Rating') self.date_field_name = config.get('date_field_name', 'Date') self.directors_field_name = config.get('directors_field_name', 'Directors') self.poster_field_name = config.get('poster_field_name', 'Poster') self.year_field_name = config.get('year_field_name', 'Year') self.genres_field_name = config.get('genres_field_name', 'Genres') self.cast_field_name = config.get('cast_field_name', 'Cast') self.runtime_field_name = config.get('runtime_field_name', 'Runtime') self.imdb_field_name = config.get('imdb_field_name', 'IMDB')
def get_weather(lat, lon, bold): err = '' ''' You will need an API key to get weather data. Register for your free key at http:// www.wunderground.com/weather/api ''' api_key = keychain.get_password('wunderground', 'api') If api_key == None: api_key = console.input_alert('No API Key', 'You must register for a free api key at https://www.wunderground.com/weather/api and enter it here:', '', 'Ok', hide_cancel_button = False) If api_key <> '': api_key = keychain.set_password('wunderground', 'api', api_key) api_key = keychain.get_password('wunderground', 'api')
def search(sender): options = load_options() # TODO: Check options to make sure they exist and exit with message if they # don't. # TODO: Add a progress indicator and thread search so a long search doesn't # appear to lock it up if 'username' in options: password = keychain.get_password(keychain_service, options['username']) computer_name = v['computer_name'].text if not computer_name: return server = Server(options['server'], get_info=ALL) conn = Connection(server, options['username'], password, auto_bind=True) conn.search(search_base=options['search_base'], search_filter='(&(cn={name}))'.format(name=computer_name), search_scope=SUBTREE, attributes=ALL_ATTRIBUTES, get_operational_attributes=True) result = json.loads(conn.response_to_json()) if 'ms-Mcs-AdmPwd' in result['entries'][0]['attributes']: passwd = result['entries'][0]['attributes']['ms-Mcs-AdmPwd'] else: passwd = 'Not set.' distinguished_name = result['entries'][0]['attributes']['distinguishedName'] v['text_password'].text = passwd v['text_name'].text = distinguished_name conn.unbind()
def __init__(self,tf): self.tf = tf self.tfo = ObjCInstance(tf).textField() # UITextField is subview of ui.TextField self.multitouch_enabled = True self.touch_actives = {} self.touch_n = 0 #self.sounds = ['piano:C3', 'piano:D3', 'piano:E3', 'piano:F3', 'piano:G3', 'piano:A3'] self.Japanese_Braille = { '1':'あ', '12':'い', '14':'う', '124':'え', '24':'お', '16':'か', '1246':'け', '123456':'め' } # get/set circle positions settings_str = keychain.get_password('Braille','settings') if settings_str: self.settings = ast.literal_eval(settings_str) # convert str -> dict else: self.settings = { 'portrait':{'1':(100,100),'2':(100,400),'3':(100,700),'4':(500,100),'5':(500,400),'6':(500,700)}, 'landscape':{'1':(100,100),'2':(100,320),'3':(100,540),'4':(700,100),'5':(700,320),'6':(700,540)} } self.save_settings() b_close = ui.Button() b_close.frame = (0,30,48,48) b_close.background_image =ui.Image.named('iob:ios7_close_outline_32') b_close.action = self.close_button_action self.add_subview(b_close)
def get_token(): token = keychain.get_password('gistcheck', 'gistcheck') if token is None: u, p = console.login_alert('GitHub Login') token = auth(u, p)['token'] keychain.set_password('gistcheck', 'gistcheck', token) return token
def git_push(args): parser = argparse.ArgumentParser(prog='git push' , usage='git push [http(s)://<remote repo> or remote] [-u username[:password]]' , description="Push to a remote repository") parser.add_argument('url', type=str, nargs='?', help='URL to push to') parser.add_argument('-u', metavar='username[:password]', type=str, required=False, help='username[:password]') result = parser.parse_args(args) user, sep, pw = result.u.partition(':') if result.u else (None,None,None) repo = _get_repo() origin='origin' if not result.url: result.url = repo.remotes.get('origin','') if result.url in repo.remotes: origin=result.url result.url=repo.remotes.get(origin) branch_name = os.path.join('refs','heads', repo.active_branch) #'refs/heads/%s' % repo.active_branch print "Attempting to push to: {0}, branch: {1}".format(result.url, branch_name) netloc = urlparse.urlparse(result.url).netloc keychainservice = 'stash.git.{0}'.format(netloc) if sep and not user: # -u : clears keychain for this server for service in keychain.get_services(): if service[0]==keychainservice: keychain.delete_password(*service) #Attempt to retrieve user if not user and SAVE_PASSWORDS and result.url.startswith('http'): try: user = dict(keychain.get_services())[keychainservice] except KeyError: user = raw_input('Enter username: '******'Enter password: '******'Enter credentials for {0}'.format(netloc)) if user: if not pw and SAVE_PASSWORDS: pw = keychain.get_password(keychainservice, user) #Check again, did we retrieve a password? if not pw: user, pw = console.login_alert('Enter credentials for {0}'.format(netloc), login=user) #pw = getpass.getpass('Enter password for {0}: '.format(user)) host_with_auth='{}:{}@{}'.format(user,pw,netloc) url=urlparse.urlunparse( urlparse.urlparse(result.url)._replace( netloc=host_with_auth)) porcelain.push(repo.repo.path, url, branch_name) keychain.set_password(keychainservice, user, pw) else: porcelain.push(repo.repo.path, result.url, branch_name) print 'success!'
def get_token(): token = keychain.get_password('gistcheck','gistcheck') if token is None: u, p = console.login_alert('GitHub Login') token = auth(u, p)['token'] keychain.set_password('gistcheck','gistcheck',token) return token
def main(): global LOG LOG = logging.getLogger() LOG.setLevel(logging.INFO) if DEBUG > 1: LOG.setLevel(logging.DEBUG) c = logging.StreamHandler() c.setFormatter(TradervueLogFormatter()) LOG.addHandler(c) args = get_args(sys.argv[1:]) actions = { 'set_password': set_password, 'delete_password': delete_password, 'new_note': new_note, 'update_journal': update_journal } ok = False if args['action'] not in actions: raise ValueError("Invalid action '%s'" % (args['action'])) elif args['action'].endswith('_password'): ok = actions[args['action']](args) else: p = keychain.get_password(KEYCHAIN_ID, args['user']) if p is None: # Request one from the user p = console.password_alert("Tradervue Credentials", args['user']) else: tv = Tradervue(args['user'], p, USER_AGENT, verbose_http = True if DEBUG > 1 else False) ok = actions[args['action']](args, tv) return 0 if ok else 1
def _get_key(self): """Retrieve the working copy key or prompt for a new one.""" key = keychain.get_password('wcSync', 'xcallback') if not key: key = console.password_alert('Working Copy Key') keychain.set_password('wcSync', 'xcallback', key) return key
def set_get_user_pass(service): # store username and password in keychain if not found if not service in [x[0] for x in keychain.get_services()]: print 'Keychain does not contain %s username and password.' % service username = raw_input('Enter your %s username and press enter:' % service) password = raw_input('Enter your %s password and press enter:' % service) print 'Username %s and password saved for %s.' % (username, service) keychain.set_password(service, username, password) else: # get the username---can be multiple accounts for one service usernamelist = [ x[1] for x in keychain.get_services() if x[0] == service ] if len(usernamelist) > 1: print 'Multiple usernames were found for %s.' % service for uname in enumerate(usernamelist): print ' [%d]: %s' % (uname[0] + 1, uname[1]) unum = int( raw_input('Enter the number of the correct one:').strip()) - 1 username = usernamelist[unum] else: username = usernamelist[0] # get the password based on correct username password = keychain.get_password(service, username) return username, password
def main(): ### CHANGE THESE VALUES: to = console.input_alert('Send Email To', 'Enter an email address below') subject = console.input_alert('Subject', 'Enter the subject of the email below') gmail_pwd = keychain.get_password('Gmail', '*****@*****.**') gmail_user = '******' #Load a sample image, modify as needed: image = clipboard.get_image() print 'Connecting...' smtpserver = smtplib.SMTP("smtp.gmail.com", 587) console.show_activity() smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_user, gmail_pwd) print 'Preparing message...' outer = MIMEMultipart() outer['Subject'] = subject outer['To'] = to outer['From'] = gmail_user outer.preamble = 'You will not see this in a MIME-aware email reader.\n' attachment = get_attachment(image) outer.attach(attachment) composed = outer.as_string() print 'Sending...' smtpserver.sendmail(gmail_user, to, composed) smtpserver.close() console.hide_activity() sound.play_effect('Bleep') print 'Done.'
def set_get_user_pass(service): # store username and password in keychain if not found if not service in [x[0] for x in keychain.get_services()]: print 'Keychain does not contain %s username and password.' % service username = raw_input('Enter your %s username and press enter:' % service) password = raw_input('Enter your %s password and press enter:' % service) print 'Username %s and password saved for %s.' % (username, service) keychain.set_password(service, username, password) else: # get the username---can be multiple accounts for one service usernamelist = [x[1] for x in keychain.get_services() if x[0]==service] if len(usernamelist) > 1: print 'Multiple usernames were found for %s.' % service for uname in enumerate(usernamelist): print ' [%d]: %s'%(uname[0]+1, uname[1]) unum = int(raw_input('Enter the number of the correct one:').strip()) - 1 username = usernamelist[unum] else: username = usernamelist[0] # get the password based on correct username password = keychain.get_password(service, username) return username, password
def main(): tasks = sys.argv[1].splitlines() ### CHANGE THESE VALUES: # My login script -- you'll need to delete / comment this and add your info below. to = keychain.get_password('omnifocus', 'maildrop_address') # to = 'Your_OmniGroup_MailDrop_Address' # gmail_user = '******' # comment my b64 stuff in the next line gmail_user = b64decode('bjhoZW5yaWVAZ21haWwuY29t') gmail_pwd = keychain.get_password('multilineomnifocus', gmail_user) console.clear() print('Starting SMTP Server') smtpserver = smtplib.SMTP("smtp.gmail.com", 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_user, gmail_pwd) for task in tasks: outer = MIMEMultipart() outer['Subject'] = task outer['To'] = to outer['From'] = gmail_user outer.preamble = 'You will not see this in a MIME-aware email reader.\n' composed = outer.as_string() print('Sending Task ' + str(tasks.index(task) + 1)) smtpserver.sendmail(gmail_user, to, composed) smtpserver.close() print('Done') console.clear() # Added to kind of support callbacks while maintaining # backwards compatibility. return_to = sys.argv[-1] if len(sys.argv) > 2 and webbrowser.open(return_to): webbrowser.open(return_to) else: webbrowser.open('drafts:')
def main(): tasks = sys.argv[1].splitlines() ### CHANGE THESE VALUES: # My login script -- you'll need to delete / comment this and add your info below. to = keychain.get_password('omnifocus','maildrop_address') # to = 'Your_OmniGroup_MailDrop_Address' # gmail_user = '******' # comment my b64 stuff in the next line gmail_user = b64decode('bjhoZW5yaWVAZ21haWwuY29t') gmail_pwd = keychain.get_password('multilineomnifocus',gmail_user) console.clear() print 'Starting SMTP Server' smtpserver = smtplib.SMTP("smtp.gmail.com", 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_user, gmail_pwd) for task in tasks: outer = MIMEMultipart() outer['Subject'] = task outer['To'] = to outer['From'] = gmail_user outer.preamble = 'You will not see this in a MIME-aware email reader.\n' composed = outer.as_string() print 'Sending Task ' + str(tasks.index(task) + 1) smtpserver.sendmail(gmail_user, to, composed) smtpserver.close() print 'Done' console.clear() # Added to kind of support callbacks while maintaining # backwards compatibility. return_to = sys.argv[-1] if len(sys.argv) > 2 and webbrowser.open(return_to): webbrowser.open(return_to) else: webbrowser.open('drafts:')
def get_encryption_password(): password = keychain.get_password('EncryptedPDFs', 'password') if password: return password.encode('ascii') password = console.secure_input( 'Enter password to encrypt PDFs: ').rstrip() keychain.set_password('EncryptedPDFs', 'password', password) return password
def load_dropbox_data(username): """load dropbox access information for username.""" encoded = keychain.get_password(DB_SERVICE, username) if encoded is None: return None dumped = base64.b64decode(encoded) raw = pickle.loads(dumped) return raw
def on_create(self, path): password = keychain.get_password(path) if password == None: ask_password_and_mount(path) if mount_volume(path, password): logger.info("mounted path %s" % path) else: ask_password_and_mount(path)
def getGithubPassword(username): service = 'github' password = keychain.get_password(service, username) if password == None: print("Enter password for user", username) password = console.secure_input() keychain.set_password(service, username, password) return password
def getGithubPassword(username): service = 'github' password = keychain.get_password(service, username) if password == None: print "Enter password for user", username password = console.secure_input() keychain.set_password(service, username, password) return password
def setup_gh(): keychainservice='stash.git.github.com' user = dict(keychain.get_services())[keychainservice] pw = keychain.get_password(keychainservice, user) g=Github(user,pw) u=g.get_user() return g, u
def _get_key(self): ''' Retrieve the working copy key or prompt for a new one. ''' key = keychain.get_password('wcSync', 'xcallback') if not key: key = console.password_alert('Working Copy Key') keychain.set_password('wcSync', 'xcallback', key) return key
def setup_gh(): keychainservice = 'stash.git.github.com' user = dict(keychain.get_services())[keychainservice] pw = keychain.get_password(keychainservice, user) g = Github(user, pw) u = g.get_user() return g, u
def delete_password(args): if keychain.get_password(KEYCHAIN_ID, args['user']) is None: LOG.error("No password was set for %s" % (args['user'])) return False else: keychain.delete_password(KEYCHAIN_ID, args['user']) LOG.info("Deleted credentials for %s" % (args['user'])) return True
def load_dropbox_data(): """load dropbox access information.""" encoded = keychain.get_password("stash:mc", "dropbox") if encoded is None: return None dumped = base64.b64decode(encoded) raw = pickle.loads(dumped) return raw
def _get_key(self): ''' Retrieve the working copy key or prompt for a new one. See https://github.com/ahenry91/wc_sync ''' key = keychain.get_password('wcSync', 'xcallback') if not key: key = console.password_alert('Working Copy Key') keychain.set_password('wcSync', 'xcallback', key) return key
def WC_callback_key(overwrite_key=False): service = "Working Copy" # UUID appended to avoid collision with another script # (generated on original dev machine) account = "x_callback_url_6653ee08-4c43-4453-a400-c5de315b0725" key = keychain.get_password(service, account) if overwrite_key or not key: key = console.input_alert("Enter Working Copy URL key:") keychain.set_password(service, account, key) return key
def test_against_pythonista_keychain(): import keychain set_password('s', 'a', 'password') assert (keychain.get_password('s', 'a') == 'password') keychain.set_password('s', 'a', 'anotherone') assert (get_password('s', 'a') == 'anotherone') keychain.delete_password('s', 'a') assert (get_password('s', 'a') is None)
def connect_to_device(ssh): print "\n\nConnecting to device..." keys = ssh.get_host_keys() keys.add(hostname, 'ssh-rsa', public_key) password = keychain.get_password(hostname, username) ssh.connect(hostname, username=username, password=password) shell = ssh.invoke_shell() print "Connected to " + hostname + "." shell.send("term len 0\n") return shell
def push_action(self, sender): # pdb.set_trace() user, sep, pw = (None, None, None) repo = self._get_repo() remote = self.view['remote'].text if remote in self.remotes_iterator(): remote = repo.remotes.get(remote, '') branch_name = os.path.join( 'refs', 'heads', repo.active_branch) #'refs/heads/%s' % repo.active_branch # tODO use remote branch_name netloc = urlparse.urlparse(remote).netloc keychainservice = 'shellista.git.{0}'.format(netloc) #define some callbacks for use by uidialog def push_callback(user, pw): print "Attempting to push to: {0}, branch: {1}".format( remote, branch_name) console.show_activity() if user: try: parsedurl = urlparse.urlparse(remote) host_with_auth = '{}:{}@{}'.format(user, pw, parsedurl.netloc) url = urlparse.urlunparse( parsedurl._replace(netloc=host_with_auth)) porcelain.push(repo.path, url, branch_name) keychain.set_password(keychainservice, user, pw) except urllib2.URLError: console.hide_activity() console.hud_alert('push failed', 'error') return else: porcelain.push(repo.repo, result.url, branch_name) console.hide_activity() console.hud_alert('push complete') def push_callback_dict(d): push_callback(d['username'], d['password']) #Attempt to retrieve user try: user = dict(keychain.get_services())[keychainservice] pw = keychain.get_password(keychainservice, user) if pw: push_callback(user, pw) else: raise KeyError except KeyError: self.get_pass(netloc, push_callback_dict)
def get_access_token(): token_str = keychain.get_password('dropbox', app_key) if token_str: key, secret = pickle.loads(token_str) return session.OAuthToken(key, secret) request_token = get_request_token() sess = session.DropboxSession(app_key, app_secret, access_type) access_token = sess.obtain_access_token(request_token) token_str = pickle.dumps((access_token.key, access_token.secret)) keychain.set_password('dropbox', app_key, token_str) return access_token
def shorten_url(long_url): USER = '******' API_KEY = keychain.get_password('bitly', USER) bitly_url = 'http://api.bit.ly/v3/shorten' s = requests.Session() payload = {'login': USER, 'APIKEY': API_KEY, 'URI': long_url} short_url = s.get(bitly_url, params = payload).json['data']['url'] return short_url
def connect_to_device(ssh): print "\n\nConnecting to device..." keys = ssh.get_host_keys() keys.add(hostname,'ssh-rsa',public_key) password = keychain.get_password(hostname, username) ssh.connect(hostname,username=username,password=password) shell = ssh.invoke_shell() print "Connected to " + hostname + "." shell.send("term len 0\n") return shell
def show_options(sender): options = load_options() if 'server' in options: options_view['server'].text = options['server'] if 'search_base' in options: options_view['search_base'].text = options['search_base'] if 'username' in options: options_view['username'].text = options['username'] password = keychain.get_password(keychain_service, options['username']) if password: options_view['password'].text = password options_view.present('sheet')
def git_push(args): parser = argparse.ArgumentParser(prog='git push' , usage='git push [http(s)://<remote repo>] [-u username[:password]]' , description="Push to a remote repository") parser.add_argument('url', type=str, nargs='?', help='URL to push to') parser.add_argument('-u', metavar='username[:password]', type=str, required=False, help='username[:password]') result = parser.parse_args(args) user, sep, pw = result.u.partition(':') if result.u else (None,None,None) repo = _get_repo() #Try to get the remote origin if not result.url: result.url = repo.remotes.get('origin','') branch_name = os.path.join('refs','heads', repo.active_branch) #'refs/heads/%s' % repo.active_branch print "Attempting to push to: {0}, branch: {1}".format(result.url, branch_name) netloc = urlparse.urlparse(result.url).netloc keychainservice = 'shellista.git.{0}'.format(netloc) if sep and not user: # -u : clears keychain for this server for service in keychain.get_services(): if service[0]==keychainservice: keychain.delete_password(*service) #Attempt to retrieve user if not user and SAVE_PASSWORDS: try: user = dict(keychain.get_services())[keychainservice] except KeyError: user, pw = console.login_alert('Enter credentials for {0}'.format(netloc)) if user: if not pw and SAVE_PASSWORDS: pw = keychain.get_password(keychainservice, user) #Check again, did we retrieve a password? if not pw: user, pw = console.login_alert('Enter credentials for {0}'.format(netloc), login=user) #pw = getpass.getpass('Enter password for {0}: '.format(user)) opener = auth_urllib2_opener(None, result.url, user, pw) porcelain.push(repo.repo, result.url, branch_name, opener=opener) keychain.set_password(keychainservice, user, pw) else: porcelain.push(repo.repo, result.url, branch_name)
def connect_to_wlc(ssh): print "\n\nConnecting to WLC..." keys = ssh.get_host_keys() keys.add(hostname, 'ssh-rsa', public_key) ssh.connect(hostname, username='******', password='******') password = keychain.get_password(hostname, username) shell = ssh.invoke_shell() print "Connected to WLC." shell.send(username + "\n") shell.send(password + "\n") shell.send("config paging disable\n") return shell
def get_access_token(): token_str = keychain.get_password('dropbox', app_key) if token_str: key, secret = token_str.split(',') return session.OAuthToken(key, secret) request_token = get_request_token() sess = session.DropboxSession(app_key, app_secret, access_type) access_token = sess.obtain_access_token(request_token) key = access_token.key.decode('ascii') secret = access_token.secret.decode('ascii') token_str = key + ',' + secret keychain.set_password('dropbox', app_key, token_str) return session.OAuthToken(key, secret)
def connect_to_wlc(ssh): print "\n\nConnecting to WLC..." keys = ssh.get_host_keys() keys.add(hostname,'ssh-rsa',public_key) ssh.connect(hostname,username='******',password='******') password = keychain.get_password(hostname, username) shell = ssh.invoke_shell() print "Connected to WLC." shell.send(username + "\n") shell.send(password + "\n") shell.send("config paging disable\n") return shell
def get_credentials(svc): f = filter(lambda x: x[0] == svc, keychain.get_services()) res = [x for x in f] if not res: usr, pwd = console.login_alert(svc) keychain.set_password(svc, usr, pwd) return usr, pwd return (res[0][1], keychain.get_password(*res[0]))
def commit(): gist = get_gist_id(editor.get_path()) if gist is not None: token = keychain.get_password('gistcheck','gistcheck') if token is None: u, p = console.login_alert('GitHub Login') r = json.loads(auth(u, p)) print r token = r['token'] keychain.set_password('gistcheck','gistcheck',token) fname = os.path.basename(editor.get_path()) m = console.input_alert('Edit Description','Enter a new description:','') if m == '': m = None return edit(gist,{fname:editor.get_text()},token,m)
def get_apikey(service="", account=""): assert service is not None and account is not None d = {} d.update(keychain.get_services()) if service in d: assert d.get(service, "") == account PWD = keychain.get_password(service, account) touchid_status = 0 touchid_status = authenticate("Authenticate API lookup", allow_passcode=True, timeout=10) if touchid_status: return PWD else: sys.stderr.write("Bad fingerprint!") else: raise Exception("API key not found")
def push_action(self,sender): # pdb.set_trace() user, sep, pw = (None,None,None) repo = self._get_repo() remote=self.view['remote'].text if remote in self.remotes_iterator(): remote = repo.remotes.get(remote,'') branch_name = os.path.join('refs','heads', repo.active_branch) #'refs/heads/%s' % repo.active_branch # tODO use remote branch_name netloc = urlparse.urlparse(remote).netloc keychainservice = 'shellista.git.{0}'.format(netloc) #define some callbacks for use by uidialog def push_callback(user,pw): print "Attempting to push to: {0}, branch: {1}".format(remote, branch_name) console.show_activity() if user: try: opener = auth_urllib2_opener(None, remote, user, pw) porcelain.push(repo.path, remote, branch_name, opener=opener) keychain.set_password(keychainservice, user, pw) except urllib2.URLError: console.hide_activity() console.hud_alert('push failed','error') return else: porcelain.push(repo.repo, result.url, branch_name) console.hide_activity() console.hud_alert('push complete') def push_callback_dict(d): push_callback(d['username'],d['password']) #Attempt to retrieve user try: user = dict(keychain.get_services())[keychainservice] pw = keychain.get_password(keychainservice, user) if pw: push_callback(user,pw) else: raise KeyError except KeyError: self.get_pass(netloc,push_callback_dict)
def connect(self): self.api = onedrive.OneDriveAPI(client_id=self.app_key, client_secret=self.app_secret) token_str = keychain.get_password('onedrive', self.app_key) if token_str: at, ac, ar = pickle.loads(token_str) self.api.auth_access_token = at self.api.auth_refresh_token = ar self.auth_code = ac self.api.auth_get_token() else: request_token = self._get_request_token() self.api.auth_user_process_url(request_token) self.api.auth_get_token() keychain.set_password( 'onedrive', self.app_key, pickle.dumps((self.api.auth_access_token, self.api.auth_code, self.api.auth_refresh_token)))
def connect(self): self.api = onedrive.OneDriveAPI( client_id=self.app_key, client_secret=self.app_secret) token_str = keychain.get_password('onedrive', self.app_key) if token_str: at, ac, ar = pickle.loads(token_str) self.api.auth_access_token = at self.api.auth_refresh_token = ar self.auth_code = ac self.api.auth_get_token() else: request_token = self._get_request_token() self.api.auth_user_process_url(request_token) self.api.auth_get_token() keychain.set_password('onedrive', self.app_key, pickle.dumps(( self.api.auth_access_token, self.api.auth_code, self.api.auth_refresh_token )))
def get_password_from_keychain(service, account, message=None): ''' Retrieve the working copy key or prompt for a new one. See https://github.com/ahenry91/wc_sync ''' if not message: message = "Enter password for account '%s' of service '%s'" % (account, service) key = keychain.get_password(service, account) if not key: try: key = console.password_alert(message) except KeyboardInterrupt as k: key = None if key: keychain.set_password(service, account, key) else: keychain.delete_password(service, account) return key
# Text is entered via input alert or third-party launcher # From Drafts: pythonista://EvernoteTextShare?action=run&argv=[[title]]&argv=[[body]] # Token is stored in Keychain, note is saved in default notebook # Based on Brett Kelly's Python code: https://gist.github.com/inkedmn/4074431 # and Ole Zorn's demo scripts: http://omz-software.com/pythonista/forums/discussion/203/using-the-evernote-sdk-in-pythonista # Requires Evernote dev token: https://www.evernote.com/api/DeveloperToken.action import keychain import clipboard import console import sys sys.path.append('evernote-sdk') # import token stored in Pythonista's keychain auth_token = keychain.get_password('evernote','USERNAME') # Construct URL. Replace "googlechromes://" with "safari-https://" if you want to open the note in Safari EN_HOST = "www.evernote.com" EN_URL = "googlechromes://%s" % EN_HOST console.clear() numArgs = len(sys.argv) # Count arguments, if less than 3 enter title and text manually. Use with apps like Drafts # and Launch Center Pro if numArgs < 3: title = console.input_alert('Note Title', 'Enter the title of your note') body = console.input_alert('Note Text', 'Enter the text of your note') else: print "Text received from another app, processing..."
import editor import ftplib import console import StringIO import keychain import pickle import cgi import sys # Uncomment this line to reset stored password # keychain.delete_password('vaughanje', 'editorial') login = keychain.get_password('vaughanje', 'editorial') if login is not None: user, pw = pickle.loads(login) else: user, pw = console.login_alert('FTPS Login Needed', 'No login credentials found.') pickle_token = pickle.dumps((user, pw)) keychain.set_password('vaughanje', 'editorial', pickle_token) # remotePath = "/public_html/blog/source/" host = "crawlab.org" port = 21 docTitle = console.input_alert("Filename", "Enter File Name")