Python getpass.getuser() Examples
The following are 30
code examples of getpass.getuser().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
getpass
, or try the search function
.
Example #1
Source File: h5io.py From westpa with MIT License | 6 votes |
def stamp_creator_data(h5group, creating_program = None): '''Mark the following on the HDF5 group ``h5group``: :creation_program: The name of the program that created the group :creation_user: The username of the user who created the group :creation_hostname: The hostname of the machine on which the group was created :creation_time: The date and time at which the group was created, in the current locale. :creation_unix_time: The Unix time (seconds from the epoch, UTC) at which the group was created. This is meant to facilitate tracking the flow of data, but should not be considered a secure paper trail (after all, anyone with write access to the HDF5 file can modify these attributes). ''' now = time.time() attrs = h5group.attrs attrs['creation_program'] = creating_program or sys.argv[0] or 'unknown program' attrs['creation_user'] = getpass.getuser() attrs['creation_hostname'] = socket.gethostname() attrs['creation_unix_time'] = now attrs['creation_time'] = time.strftime('%c', time.localtime(now))
Example #2
Source File: devappserver2.py From browserscope with Apache License 2.0 | 6 votes |
def _generate_storage_paths(app_id): """Yield an infinite sequence of possible storage paths.""" if sys.platform == 'win32': # The temp directory is per-user on Windows so there is no reason to add # the username to the generated directory name. user_format = '' else: try: user_name = getpass.getuser() except Exception: # The possible set of exceptions is not documented. user_format = '' else: user_format = '.%s' % user_name tempdir = tempfile.gettempdir() yield os.path.join(tempdir, 'appengine.%s%s' % (app_id, user_format)) for i in itertools.count(1): yield os.path.join(tempdir, 'appengine.%s%s.%d' % (app_id, user_format, i))
Example #3
Source File: ObjectStore.py From pcocc with GNU General Public License v3.0 | 6 votes |
def put_meta(self, name, revision, kind, data_blobs, custom_meta=None): self._validate_name(name) h = self._hash_meta(name, revision) target = self.get_obj_path('meta', h) meta = {} meta['name'] = name meta['revision'] = revision meta['kind'] = kind meta['owner'] = getpass.getuser() meta['timestamp'] = time.time() meta['data_blobs'] = data_blobs meta['custom_meta'] = custom_meta # Check that all the data blobs referred in the meta data are # already in the repo for b in data_blobs: self.get_obj_path('data', b, True) with open(target, 'w') as f: yaml.safe_dump(meta, f) return meta
Example #4
Source File: chrome.py From chrome_password_grabber with GNU General Public License v3.0 | 6 votes |
def __init__(self): """ Linux Initialization Function """ my_pass = 'peanuts'.encode('utf8') bus = secretstorage.dbus_init() collection = secretstorage.get_default_collection(bus) for item in collection.get_all_items(): if item.get_label() == 'Chrome Safe Storage': my_pass = item.get_secret() break iterations = 1 salt = b'saltysalt' length = 16 kdf = import_module('Crypto.Protocol.KDF') self.key = kdf.PBKDF2(my_pass, salt, length, iterations) self.dbpath = f"/home/{getuser()}/.config/google-chrome/Default/"
Example #5
Source File: textio.py From westpa with MIT License | 6 votes |
def __init__(self, output_file, mode='wt', emit_header=None): if hasattr(output_file, 'write'): self._file = output_file else: self._file = open(output_file, mode) self._header_written = False self._header_lines = [] self.write_header('created by program: {}'.format(sys.argv[0] or 'unknown program')) self.write_header('created by user: {}'.format(getpass.getuser())) self.write_header('created on host: {}'.format(socket.gethostname())) self.write_header('created at: {}'.format(time.strftime('%c', time.localtime(time.time())))) if emit_header is not None: self.emit_header = emit_header else: self.emit_header = self.__class__.emit_header
Example #6
Source File: chrome.py From chrome_password_grabber with GNU General Public License v3.0 | 6 votes |
def __init__(self): """ Mac Initialization Function """ my_pass = subprocess.Popen( "security find-generic-password -wa 'Chrome'", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, _ = my_pass.communicate() my_pass = stdout.replace(b'\n', b'') iterations = 1003 salt = b'saltysalt' length = 16 kdf = import_module('Crypto.Protocol.KDF') self.key = kdf.PBKDF2(my_pass, salt, length, iterations) self.dbpath = (f"/Users/{getuser()}/Library/Application Support/" "Google/Chrome/Default/")
Example #7
Source File: Privilege.py From 3vilTwinAttacker with MIT License | 6 votes |
def Qui(self): self.user = QComboBox() self.user.addItem(getpass.getuser()) self.btn_cancel = QPushButton("Cancel") self.btn_ok = QPushButton("Ok") self.Editpassword = QLineEdit(self) self.Editpassword.setFocus() #temporary self.Editpassword.setEchoMode(QLineEdit.Password) self.btn_cancel.clicked.connect(self.close) self.btn_ok.clicked.connect(self.function_ok) self.btn_ok.setDefault(True) self.frm.addRow("User:", self.user) self.frm.addRow("Password:", self.Editpassword) self.grid = QGridLayout() self.grid.addWidget(self.btn_cancel, 1,2) self.grid.addWidget(self.btn_ok, 1,3) self.Main.addLayout(self.frm) self.Main.addLayout(self.grid) self.setLayout(self.Main)
Example #8
Source File: __init__.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_system_username(): """ Try to determine the current system user's username. :returns: The username as a unicode string, or an empty string if the username could not be determined. """ try: result = getpass.getuser() except (ImportError, KeyError): # KeyError will be raised by os.getpwuid() (called by getuser()) # if there is no corresponding entry in the /etc/passwd file # (a very restricted chroot environment, for example). return '' if six.PY2: try: result = result.decode(DEFAULT_LOCALE_ENCODING) except UnicodeDecodeError: # UnicodeDecodeError - preventive treatment for non-latin Windows. return '' return result
Example #9
Source File: crypto.py From aegea with Apache License 2.0 | 6 votes |
def ensure_ssh_key(name=None, base_name=__name__, verify_pem_file=True): if name is None: from getpass import getuser from socket import gethostname name = base_name + "." + getuser() + "." + gethostname().split(".")[0] try: ec2_key_pairs = list(resources.ec2.key_pairs.filter(KeyNames=[name])) if verify_pem_file and not os.path.exists(get_ssh_key_path(name)): msg = "Key {} found in EC2, but not in ~/.ssh." msg += " Delete the key in EC2, copy it to {}, or specify another key." raise KeyError(msg.format(name, get_ssh_key_path(name))) except ClientError as e: expect_error_codes(e, "InvalidKeyPair.NotFound") ec2_key_pairs = None if not ec2_key_pairs: ssh_key = ensure_local_ssh_key(name) resources.ec2.import_key_pair(KeyName=name, PublicKeyMaterial=get_public_key_from_pair(ssh_key)) logger.info("Imported SSH key %s", get_ssh_key_path(name)) add_ssh_key_to_agent(name) return name
Example #10
Source File: rds.py From aegea with Apache License 2.0 | 6 votes |
def create(args): create_args = dict(DBInstanceIdentifier=args.name, AllocatedStorage=args.storage, Engine=args.engine, StorageType=args.storage_type, StorageEncrypted=True, AutoMinorVersionUpgrade=True, MultiAZ=False, MasterUsername=args.master_username or getpass.getuser(), MasterUserPassword=args.master_user_password, VpcSecurityGroupIds=args.security_groups, DBInstanceClass=args.db_instance_class, Tags=encode_tags(args.tags), CopyTagsToSnapshot=True) if args.db_name: create_args.update(DBName=args.db_name) if args.engine_version: create_args.update(EngineVersion=args.engine_version) clients.rds.create_db_instance(**create_args) clients.rds.get_waiter("db_instance_available").wait(DBInstanceIdentifier=args.name) instance = clients.rds.describe_db_instances(DBInstanceIdentifier=args.name)["DBInstances"][0] return {k: instance[k] for k in ("Endpoint", "DbiResourceId", "DBInstanceStatus")}
Example #11
Source File: identity.py From sawtooth-core with Apache License 2.0 | 5 votes |
def _read_signer(key_filename): """Reads the given file as a hex key. Args: key_filename: The filename where the key is stored. If None, defaults to the default key for the current user. Returns: Signer: the signer Raises: CliException: If unable to read the file. """ filename = key_filename if filename is None: filename = os.path.join(os.path.expanduser('~'), '.sawtooth', 'keys', getpass.getuser() + '.priv') try: with open(filename, 'r') as key_file: signing_key = key_file.read().strip() except IOError as e: raise CliException('Unable to read key file: {}'.format(str(e))) try: private_key = Secp256k1PrivateKey.from_hex(signing_key) except ParseError as e: raise CliException('Unable to read key in file: {}'.format(str(e))) context = create_context('secp256k1') crypto_factory = CryptoFactory(context) return crypto_factory.new_signer(private_key)
Example #12
Source File: validate.py From cloudify-manager-blueprints with Apache License 2.0 | 5 votes |
def _validate_ssh_user(): current_user = getpass.getuser() ctx.logger.info('Validating SSH user ({0})...'.format(current_user)) try: subprocess.check_call(['sudo', '-n', 'true']) except Exception as ex: return _error("Failed executing 'sudo'. Please ensure that the " "provided SSH user ({0}) is allowed to SSH to the " "manager's machine without a password (using key-" "based authentication), execute 'sudo' commands " "over SSH, and impersonate other users using " "'sudo -u'. (Error: {1})".format(current_user, ex))
Example #13
Source File: tmpdir.py From python-netsurv with MIT License | 5 votes |
def get_user(): """Return the current user name, or None if getuser() does not work in the current environment (see #1010). """ import getpass try: return getpass.getuser() except (ImportError, KeyError): return None
Example #14
Source File: sawset.py From sawtooth-core with Apache License 2.0 | 5 votes |
def _read_signer(key_filename): """Reads the given file as a hex key. Args: key_filename: The filename where the key is stored. If None, defaults to the default key for the current user. Returns: Signer: the signer Raises: CliException: If unable to read the file. """ filename = key_filename if filename is None: filename = os.path.join(os.path.expanduser('~'), '.sawtooth', 'keys', getpass.getuser() + '.priv') try: with open(filename, 'r') as key_file: signing_key = key_file.read().strip() except IOError as e: raise CliException('Unable to read key file: {}'.format(str(e))) try: private_key = Secp256k1PrivateKey.from_hex(signing_key) except ParseError as e: raise CliException('Unable to read key in file: {}'.format(str(e))) context = create_context('secp256k1') crypto_factory = CryptoFactory(context) return crypto_factory.new_signer(private_key)
Example #15
Source File: tasks.py From PrivacyScore with GNU General Public License v3.0 | 5 votes |
def __enter__(self): def handle_timeout(signum, frame): # kill all possible processes # TODO: this is a really bad idea # TODO: Especially with multiple worker threads, bad things are inevitable own_procs = get_processes_of_user(getuser()) for pid, cmdline in own_procs: # TODO: Argh if '/tests/' not in cmdline: continue os.kill(pid, 9) raise TimeoutError signal.signal(signal.SIGALRM, handle_timeout) signal.alarm(self.seconds)
Example #16
Source File: auth.py From floyd-cli with Apache License 2.0 | 5 votes |
def get_access_code_from_password(username, password): # Use username / password login floyd_logger.info("Login with your FloydHub username and password to run jobs.") if not username: username = click.prompt('Username', type=str, default=getpass.getuser()) username = username.strip() if not username: floyd_logger.info('You entered an empty string. Please make sure you enter your username correctly.') sys.exit(1) if not password: password = click.prompt('Password', type=str, hide_input=True) password = password.strip() if not password: floyd_logger.info('You entered an empty string. Please make sure you enter your password correctly.') sys.exit(1) login_credentials = Credentials(username=username, password=password) access_token = AuthClient().login(login_credentials) if not access_token: floyd_logger.info("Failed to login") sys.exit(1) return access_token
Example #17
Source File: test_local.py From filesystem_spec with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_strip_protocol_expanduser(): path = "file://~\\foo\\bar" if sys.platform == "win32" else "file://~/foo/bar" stripped = LocalFileSystem._strip_protocol(path) assert path != stripped assert "file://" not in stripped assert getpass.getuser() in stripped
Example #18
Source File: mock_tester.py From funcX with Apache License 2.0 | 5 votes |
def test(address): r = requests.post(address + '/register', json={'python_v': "{}.{}".format(sys.version_info.major, sys.version_info.minor), 'os': platform.system(), 'hname': platform.node(), 'username': getpass.getuser(), 'funcx_v': str(funcx.__version__) } ) print("Status code :", r.status_code) print("Json : ", r.json())
Example #19
Source File: test_socket.py From RAASNet with GNU General Public License v3.0 | 5 votes |
def connector(): server = socket.socket(socket.AF_INET) server.settimeout(1) try: # Send Key server.connect((host, port)) message = '%s$%s$%s$%s$%s' % (getlocalip(), os, key, getpass.getuser(), hostname) server.send(message.encode('utf-8')) print("Message sent: %s" % (message)) except Exception as e: print(e)
Example #20
Source File: system.py From stem with GNU Lesser General Public License v3.0 | 5 votes |
def test_user_proc(self): """ Tests the user function with a proc response. """ call_replacement = filter_system_call(['ps ']) with patch('stem.util.system.call') as call_mock: call_mock.side_effect = call_replacement # we started our tor process so it should be running with the same user pid = test.runner.get_runner().get_pid() self.assertTrue(getpass.getuser(), stem.util.system.user(pid))
Example #21
Source File: keyboard.py From BiblioPixel with MIT License | 5 votes |
def _make_thread(self): if not pynput: raise ValueError(INSTALL_ERROR) if platform.platform().startswith('Darwin'): if getpass.getuser() != 'root': log.warning(DARWIN_ROOT_WARNING, sys.argv[0]) log.info('Starting to listen for keyboard input') return Listener(self._press, self._release)
Example #22
Source File: devappserver2_test.py From browserscope with Apache License 2.0 | 5 votes |
def test_broken_getuser(self): getpass.getuser().AndRaise(Exception()) tempfile.gettempdir().AndReturn('/tmp') self.mox.ReplayAll() self.assertEqual( [os.path.join('/tmp', 'appengine.myapp'), os.path.join('/tmp', 'appengine.myapp.1'), os.path.join('/tmp', 'appengine.myapp.2')], list(itertools.islice(devappserver2._generate_storage_paths('myapp'), 3))) self.mox.VerifyAll()
Example #23
Source File: devappserver2_test.py From browserscope with Apache License 2.0 | 5 votes |
def test_working_getuser(self): getpass.getuser().AndReturn('johndoe') tempfile.gettempdir().AndReturn('/tmp') self.mox.ReplayAll() self.assertEqual( [os.path.join('/tmp', 'appengine.myapp.johndoe'), os.path.join('/tmp', 'appengine.myapp.johndoe.1'), os.path.join('/tmp', 'appengine.myapp.johndoe.2')], list(itertools.islice(devappserver2._generate_storage_paths('myapp'), 3))) self.mox.VerifyAll()
Example #24
Source File: devappserver2_test.py From browserscope with Apache License 2.0 | 5 votes |
def setUp(self): self.mox = mox.Mox() self.mox.StubOutWithMock(getpass, 'getuser') self.mox.StubOutWithMock(tempfile, 'gettempdir')
Example #25
Source File: generate_license.py From dephell with MIT License | 5 votes |
def __call__(self) -> bool: # get license object name = ' '.join(self.args.name).strip() if not name: name = 'MIT' license = licenses.get_by_id(name) if license is None: license = licenses.get_by_name(name) if license is None: self.logger.error('cannot find license with given name') return False # author name from --owner author = self.config.get('owner') # get author from `from` if not author and 'from' in self.config: loader = CONVERTERS[self.config['from']['format']] loader = loader.copy(project_path=Path(self.config['project'])) root = loader.load(self.config['from']['path']) if root.authors: author = root.authors[0] # author from project config file if not author: metainfo = PackageRoot(Path(self.config['project'])).metainfo if metainfo and metainfo.authors: author = metainfo.authors[0] # author from getuser().title if not author: author = getuser().title() # generate license text text = license.make_text(copyright='{year} {name}'.format( year=datetime.now().year, name=author, )) (Path(self.config['project']) / 'LICENSE').write_text(text) self.logger.info('license generated', extra=dict(license=license.name)) return True
Example #26
Source File: __main__.py From pulseaudio-dlna with GNU General Public License v3.0 | 5 votes |
def acquire_lock(): acquire_lock._lock_socket = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM) try: name = '/com/masmu/pulseaudio_dlna/{}'.format(getpass.getuser()) acquire_lock._lock_socket.bind('\0' + name) return True except socket.error: return False
Example #27
Source File: chrome.py From chrome_password_grabber with GNU General Public License v3.0 | 5 votes |
def __init__(self): """ Windows Initialization Function """ # search the genral chrome version path win_path = f"C:\\Users\\{getuser()}\\AppData\\Local\\Google" "\\{chrome}\\User Data\\Default\\" win_chrome_ver = [ item for item in ['chrome', 'chrome dev', 'chrome beta', 'chrome canary'] if os.path.exists(win_path.format(chrome=item)) ] self.dbpath = win_path.format(chrome=''.join(win_chrome_ver)) # self.dbpath = (f"C:\\Users\\{getuser()}\\AppData\\Local\\Google" # "\\Chrome\\User Data\\Default\\")
Example #28
Source File: test_io_raw_terminal.py From moler with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_terminal_whoami_ls(terminal_connection): terminal = terminal_connection cmd = Whoami(connection=terminal) ret = cmd() user1 = ret['USER'] cmd = Ls(connection=terminal) cmd() cmd = Whoami(connection=terminal) ret = cmd() user2 = ret['USER'] assert user1 == user2 assert getpass.getuser() == user2
Example #29
Source File: test_io_raw_terminal.py From moler with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_terminal_timeout_next_command(terminal_connection): terminal = terminal_connection max_nr = 5 for i in range(1, max_nr): cmd = Ping(connection=terminal, destination="127.0.0.1") with pytest.raises(CommandTimeout): cmd(timeout=0.3) cmd = Whoami(connection=terminal) ret = cmd() user = ret['USER'] assert getpass.getuser() == user
Example #30
Source File: test_io_raw_terminal.py From moler with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_terminal_cmd_whoami(terminal_connection): terminal = terminal_connection terminal.debug_hex_on_non_printable_chars = True terminal.debug_hex_on_all_chars = True cmd = Whoami(connection=terminal) ret = cmd() terminal.debug_hex_on_non_printable_chars = False terminal.debug_hex_on_all_chars = False assert 'USER' in ret assert ret['USER'] is not None assert getpass.getuser() == ret['USER']