def _get_credentials_for_netloc_from_keyring( self, url: str, netloc: str, username: Optional[str]) -> Optional[Dict[str, str]]: import keyring cred = keyring.get_credential(url, username) if cred is not None: return { "username": cred.username, "password": cred.password, } cred = keyring.get_credential(netloc, username) if cred is not None: return { "username": cred.username, "password": cred.password, } if username: return { "username": username, "password": None, } return None
def get_password(service): from keyring import get_credential try: return get_credential(service, "").password except AttributeError: _set_password(service) return get_credential(service, "").password
def key_delete(serviceName="", userName=""): """Deletes a key password Given the serviceName and userName, this function will delete the specified key form the Windows Credential Manager. This is a wrapper around keyring.delete_password() to work with R compliant keys saved in the Windows Credential Manager. Parameters ---------- serviceName : str The service name for the keyring object you want to delete. userName : str The username for the keyring object you want to delete. Returns ------- None The function has no return value """ #Create R Compliant Service Name serviceName = _key_create_serviceName(serviceName, userName) #Check that the key exists try: keyring.get_credential(serviceName, None).username except AttributeError: print("Cannot find a record for " + userName + " in your Windows Credential Manager. Check your inputs") raise #Delete key keyring.delete_password(serviceName, userName)
def gitcreds_get(): """Retrieve GitHub logon credentials with {keyring}. Searches for the existance of the predefined service name in Windows Credential Manager and retrieves the password. Returns ------- str GitHub logon password. """ serviceName = "git:https://github.com" #Check for current record if keyring.get_credential(serviceName, None) is None: raise RuntimeError( "Cannot find any saved git credentials in your Windows Credential Manager. Does it need added? See instructions HERE on how to add it." ) #Retrieve password userName = keyring.get_credential(serviceName, None).username passwd = keyring.get_password(serviceName, userName) return passwd
def test_set_password_fallback(passwords, fake_provider): # Ensure we are getting good credentials assert keyring.get_credential(SUPPORTED_HOST + "1234", None).password == "pass1234" assert keyring.get_password("SYSTEM", "USERNAME") is None keyring.set_password("SYSTEM", "USERNAME", "PASSWORD") assert passwords["SYSTEM", "USERNAME"] == "PASSWORD" assert keyring.get_password("SYSTEM", "USERNAME") == "PASSWORD" assert keyring.get_credential("SYSTEM", "USERNAME").username == "USERNAME" assert keyring.get_credential("SYSTEM", "USERNAME").password == "PASSWORD" # Ensure we are getting good credentials assert keyring.get_credential(SUPPORTED_HOST + "1234", None).password == "pass1234"
def key_get(serviceName="", userName=""): """Retrieves a key password Given the serviceName and userName, this function will retrieve the password for the specified key. This is a wrapper around keyring.get_password() to work with R compliant keys saved in the Windows Credential Manager. Parameters ---------- serviceName : str The service name for the keyring object you want to retrieve. userName : str The username for the keyring object you want to retrieve. Returns ------- str The saved password for the specified key. """ #Create R Compliant Service Name serviceName = _key_create_serviceName(serviceName, userName) #Check that the key exists if keyring.get_credential(serviceName, None) is None: raise RuntimeError( "Cannot find a record for " + serviceName + " in your Windows Credential Manager. Does it need added? See instructions HERE on how to add it." ) #Retrieve Key outPass = keyring.get_password(serviceName, userName) return outPass
def login(self, driver, user, pasService, pasUser): login = self.driver.find_element_by_name("Login") password = self.driver.find_element_by_name("Password") login.send_keys(user) password.send_keys( keyring.get_credential(pasService, pasUser).password) password.send_keys(Keys.RETURN)
def test_cannot_delete_password(passwords, fake_provider): # Ensure we are getting good credentials creds = keyring.get_credential(SUPPORTED_HOST + "1234", None) assert creds.username == "user1234" assert creds.password == "pass1234" with pytest.raises(keyring.errors.PasswordDeleteError): keyring.delete_password(SUPPORTED_HOST + "1234", creds.username)
def get_credentials(service_name): credentials = keyring.get_credential(service_name, None) if credentials is None: username = input("Username: ") password = getpass.getpass() keyring.set_password(service_name, username, password) else: username = credentials.username password = credentials.password return username, password
def setup(self): try: self.content = keyring.get_credential( self.name, self._MOCK_USER ) assert self.content is not None, ValueError("Got empty credentials.") except (RuntimeError, AssertionError) as e: raise AuthenticationError("Failed to load credentials '{}'.".format(self.name)) from e
def get_username_from_keyring(system): try: creds = keyring.get_credential(system, None) if creds: return creds.username except AttributeError: # To support keyring prior to 15.2 pass except Exception as exc: warnings.warn(str(exc))
def test_delete_password_fallback(passwords, fake_provider): # Ensure we are getting good credentials assert keyring.get_credential(SUPPORTED_HOST + "1234", None).password == "pass1234" passwords["SYSTEM", "USERNAME"] = "******" keyring.delete_password("SYSTEM", "USERNAME") assert keyring.get_password("SYSTEM", "USERNAME") is None assert not passwords with pytest.raises(keyring.errors.PasswordDeleteError): keyring.delete_password("SYSTEM", "USERNAME")
def get_username_from_keyring(self) -> Optional[str]: try: creds = keyring.get_credential(self.system, None) if creds: return cast(str, creds.username) except AttributeError: # To support keyring prior to 15.2 pass except Exception as exc: warnings.warn(str(exc)) return None
def connectODBC(databaseString): #Create Service Name serviceName = ":DB_conn:" + databaseString #Check that the key exists try: keyring.get_credential(serviceName, None).username except AttributeError: print("Cannot find a record for " + databaseString + " in your Windows Credential Manager. Does it need added?") print("See instructions HERE on how to add it.") raise connString = keyring.get_password(serviceName, databaseString) # print(connString) conn = pyodbc.connect(connString) return conn
def get_access_token(): if "GITHUB_ACCESS_TOKEN" in os.environ: return os.environ["GITHUB_ACCESS_TOKEN"] credential = keyring.get_credential("api.github.com", None) if credential is not None: return credential.password raise RuntimeError( "No github access token found, please set GITHUB_ACCESS_TOKEN " "environment variable or add [email protected] to your " "system keyring, e.g. run `keyring set api.github.com <username>`")
def gitcreds_delete(): """Delete GitHub logon credentials with {keyring} Deletes the GitHub login credentials from your Windows Credential Store. Returns ------- None Nothing is returned """ serviceName = "git:https://github.com" #Check for current record and delete if found if keyring.get_credential(serviceName, None) is None: print("A record for '" + serviceName + "' does not exist. No record deleted.") else: userName = keyring.get_credential(serviceName, None).username keyring.delete_password(serviceName, userName) return None
def login(self, user, pasService, pasUser): login = self.driver.find_element_by_name("Login") password = self.driver.find_element_by_name("Password") login.send_keys(Keys.CONTROL + "a") login.send_keys(Keys.DELETE) login.send_keys(user) password.send_keys(Keys.CONTROL + "a") #TODO try: with id TempPassword except: password.send_keys(Keys.DELETE) password.send_keys( keyring.get_credential(pasService, pasUser).password) password.send_keys(Keys.RETURN) WebDriverWait(self.driver, self.delay).until( EC.presence_of_element_located((By.CLASS_NAME, "email")))
def get_credential(self, *names: str, username: str | None = None) -> HTTPAuthCredential: default = HTTPAuthCredential(username=username, password=None) if not self.is_available(): return default import keyring for name in names: credential = keyring.get_credential(name, username) if credential: return HTTPAuthCredential(username=credential.username, password=credential.password) return default
def gitcreds_set(userName=''): """Set GitHub logon credentials with {keyring} Sets the GitHub login credentials that are used many applications that connect to GitHub. Parameters ---------- username : str The username of your GitHub account. Returns ------- None Nothing is returned """ serviceName = "git:https://github.com" #Check that a git credential record is not set. if keyring.get_credential(serviceName, None) is not None: raise RuntimeError( "There is already a git credentials key set in your Windows Credential Manager. If it needs changed, delete it and recreate it." ) #If userName is blank, search for the username saved in your Git config file. if userName == "": try: currentConfig = getGitConfig() except: currentConfig = None if currentConfig is None: raise RuntimeError( "userName was not specified and has not been set in your global Git configuration. Set it with 'marcpy.gitcreds.setGitConfig()`." ) else: userName = currentConfig['username'] #Create the password. keyring.set_password(serviceName, userName, getpass.getpass(prompt="Enter PAT: "))
def main(args = None): if args is None: args = sys.argv[1:] if not args or args[-1] not in COMMANDS: print("Invalid usage", file=sys.stderr) return 1 command = args.pop() stdin_args = read_stdin_args() url = "%(protocol)s://%(host)s" % stdin_args if "path" in stdin_args: url = "/".join((url, stdin_args["path"])) service = "git-credential-pykeyring+" + url if command == "get": username = stdin_args.get("username") if hasattr(keyring, "get_credential"): credential = keyring.get_credential(service, username) if credential is None: return 0 username = credential.username password = credential.password else: password = keyring.get_password(service, username) if password is None: return 0 if "username" not in stdin_args and username is not None: print("username="******"password="******"store": keyring.set_password(service, stdin_args["username"], stdin_args["password"]) elif command == "erase": keyring.delete_password(service, stdin_args["username"])
def get_credentials_windows(service_id, reset=False, attempts=3, info=None): keyring while attempts > 0: attempts -= 1 try: if reset: # an event flow trick logging.debug("resetting the credentials") raise ValueError logging.info(f"attempting to retrieve crdentials for {service_id}") kr = keyring.get_credential(service_id, None) if kr is None: #logging.warning(f"no credentials found for {service_id} in Windows registry") raise ValueError( f"no credentials found for {service_id} in Windows registry" ) return kr.username, kr.password except (ValueError, NoKeyringError) as ee: print("") print("=" * 50) print("") print( f'Please create an account for "{service_id}" by clicking "Add..."' ) print("Enter following:") print(f"Log on to: {service_id}") print("Username : your username") print("Password : your password") if info: print(info) # os.system("control keymgr.dll") # this one returns asynchronously os.system("rundll32.exe keymgr.dll, KRShowKeyMgr") reset = False else: logging.warning("number of attempts exceeded") raise ValueError( "unable to retrieve credentials. Number of attempts exceeded")
def get_repo_token(host, username): cred = keyring.get_credential(host, username) if not cred: raise Exit(f"You must set the token for {REPO_HOST} first with the set-token task.", 1) return cred.password
from ipod import Shuffler app = Flask(__name__) logging.basicConfig(level="INFO", format="%(message)s", datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True)]) log = logging.getLogger(__name__) # Config MUSIC_DIR = Path('music') PLAYLIST_NAME = 'Shuffleupagus' PLAYLIST_ID = '95f83b1d-1d5d-4626-bcdd-bf3a1a8a0b6e' USERNAME = keyring.get_credential("Pocket Casts", "username").password PASSWORD = keyring.get_credential("Pocket Casts", USERNAME).password @dataclass(frozen=True) class Episode: order: int uuid: str url: furl title: str podcast: str @classmethod def from_dict(cls, order: int, dict: t.Dict) -> "Episode": input_dict = dict.copy() input_dict["order"] = order
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Author: Ryan Tischer [email protected] import pen, pen_auth, pen_quickstart, pen_2_kafka, utils import datetime, keyring, json #must run pypen_init first to set username and password #comment to use static vars below #start secure environment var creds = (keyring.get_credential("pensando", "admin")) with open('pypen_init_data.json') as json_file: jdata = json.load(json_file) PSM_IP = jdata["ip"] PSM_TENANT = jdata["tenant"] PSM_USERNAME = creds.username PSM_PASSWD = creds.password #end secure environment vars #static PSM vars. Uncomment to use """ PSM_IP = 'https://10.29.75.21/' PSM_TENANT = 'default' PSM_USERNAME = "******" PSM_PASSWD = creds.password
def test_get_credential(only_backend, fake_provider): creds = keyring.get_credential(SUPPORTED_HOST + "1234", None) assert creds.username == "user1234" assert creds.password == "pass1234"
def test_get_credential_unsupported_host(only_backend): assert keyring.get_credential("https://example.com", None) == None
def delete_password(service): from keyring import get_credential, delete_password delete_password(service, get_credential(service, "").username)
def keyring_get(name, kr=keyring.backends.Windows): "Gets standard Keyring password." k = keyring.get_credential(kr, name) return (k.__dict__[name])
def update_picklists(item_id, sql_schema, table_name, field_map): """Updates hosted csv file which is used by Survey123 in select_from_file questions. Updates the csv file hosted in ArcGIS Online / Portal. CSV linking must be used for 'select_x_from_file' question types in the form, and content linking must be enabled on these forms. The field map dictionary shoould be constructed using the format {input_field: output_field}. Output tables must contain 'name' and 'label' fields at a minimum. Additional optional fields may be included to drive cascading select type questions. ArGIS Online or Portal login credentials must be saved in the Window Credential Manager as 'Generic Credentials'. Note: linked content csvs are currently only supported by the field application. Any changes made to picklists contained in linked content csv files will not be reflected in a Survey123 web form. Parameters ---------- item_id : str The item id of the target hosted .csv sql_schema : str String which represents the name of the schema which owns the SQL table table_name : str String which represents the name of the SQL table field_map : dict Dictionary of input SQL field names and their corresponding output csv field names """ portal_url = r'https://nps.maps.arcgis.com' # Change to portal URL once migrated # Windows credentials will need to be updated as well. Maybe make variable? agol_credentials = get_credential(portal_url, 'GRCA_GIS') # Code to initiate connection to SQL server # Update to correct windows credentials. Maybe make variable? sql_credential = get_credential('sql_login', 'postgres') conn_dict = { 'drivername': 'postgresql', # Change drivername to correct driver for target platform 'username': sql_credential.username, 'password': sql_credential.password, 'host': '127.0.0.1', # set to host IP or path 'port': '5432' } conn_url = URL.create(**conn_dict) engine = create_engine(conn_url) # Fetch item from AGOL/portal gis = GIS(url=portal_url, username=agol_credentials.username, password=agol_credentials.password) item = Item(gis, item_id) # Construct query string field_qry_list = [] for key, value in field_map.items(): field_qry_list.append(f'{key} AS {value}') field_string = ', '.join(field_qry_list) # Query SQL table sql_query = f'''SELECT {field_string} FROM {sql_schema}.{table_name};''' updated_table = read_sql_query(sql_query, engine) # Save to disk. Potential optimization is to use in-memory csv serialization, but I can't get it to work output = 'temp_csv.csv' updated_table.to_csv(output, index=False) # Push table to AGOL item.update(data=output) # Delete temporary csv file remove(output)
import getpass import requests import keyring import mysqlx import stores import sales import positions user = '******' password = '******' network_service = 'localhost' if password is None: try: user = getpass.getuser() password = keyring.get_credential(network_service, user) except: if password is None: password = getpass.getpass('Please Enter your password: '******'host': 'localhost', 'port': 33060, 'user': user, 'password': password } sess = mysqlx.get_session(creds) db = sess.get_schema('sig_ron')