当前位置: 首页>>代码示例>>Python>>正文


Python getpass.getuser方法代码示例

本文整理汇总了Python中getpass.getuser方法的典型用法代码示例。如果您正苦于以下问题:Python getpass.getuser方法的具体用法?Python getpass.getuser怎么用?Python getpass.getuser使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在getpass的用法示例。


在下文中一共展示了getpass.getuser方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
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")} 
开发者ID:kislyuk,项目名称:aegea,代码行数:24,代码来源:rds.py

示例2: ensure_ssh_key

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
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 
开发者ID:kislyuk,项目名称:aegea,代码行数:25,代码来源:crypto.py

示例3: Qui

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
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) 
开发者ID:wi-fi-analyzer,项目名称:3vilTwinAttacker,代码行数:23,代码来源:Privilege.py

示例4: __init__

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
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/") 
开发者ID:priyankchheda,项目名称:chrome_password_grabber,代码行数:20,代码来源:chrome.py

示例5: _generate_storage_paths

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
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)) 
开发者ID:elsigh,项目名称:browserscope,代码行数:20,代码来源:devappserver2.py

示例6: put_meta

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
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 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:25,代码来源:ObjectStore.py

示例7: __init__

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
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 
开发者ID:westpa,项目名称:westpa,代码行数:20,代码来源:textio.py

示例8: stamp_creator_data

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
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)) 
开发者ID:westpa,项目名称:westpa,代码行数:25,代码来源:h5io.py

示例9: get_system_username

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:23,代码来源:__init__.py

示例10: handle_user_type

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
def handle_user_type(self):
        if self.user_type == TERMINAL:
            self.user = TermUser(getpass.getuser(), self)
            self.user.tell("Welcome to Indra, " + str(self.user) + "!")
        elif self.user_type == TEST:
            self.user = TestUser(getpass.getuser(), self)
        elif self.user_type == API:
            self.user = APIUser(getpass.getuser(), self) 
开发者ID:gcallah,项目名称:indras_net,代码行数:10,代码来源:env.py

示例11: __init__

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
def __init__(self, name, preact=False,
                 postact=False, model_nm=None, props=None):
        super().__init__(name)

        self.period = 0
        self.preact = preact
        self.postact = postact
        self.disp_census = False
        self.line_graph = None
        self.line_graph_title = "Populations in "
        self.model_nm = model_nm
        if props is None:
            if model_nm is not None:
                self.props = pa.PropArgs.get_props(model_nm)
            else:
                self.props = None
        else:
            self.props = props

        user_nm = getpass.getuser()
        user_type = user.TERMINAL
        if self.props is not None:
            self.props["user_name"] = user_nm
            user_type = self.props["user_type"]
        self.user = user.User(user_nm, user_type)
        # we have to wait until user is set to do...
        if self.props is None:
            self.user.tell("Could not get props; model_nm = " + str(model_nm),
                           type=user.ERROR)
        self.menu = mm.MainMenu("Main Menu", self)

        self.image_bytes = None

        self.__init_unrestorables() 
开发者ID:gcallah,项目名称:indras_net,代码行数:36,代码来源:env.py

示例12: get_client_token

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
def get_client_token(iam_username, service):
    from getpass import getuser
    from socket import gethostname
    tok = "{}.{}.{}:{}@{}".format(iam_username, service, int(time.time()), getuser(), gethostname().split(".")[0])
    return tok[:64] 
开发者ID:kislyuk,项目名称:aegea,代码行数:7,代码来源:dns.py

示例13: import_ssh_key

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
def import_ssh_key(ctx, path):
    """
    Add an authorized key from a public key file.

    PATH must be a path to a public key file, which corresponds to
    a private key that SSH can use for authentication. Typically,
    ssh-keygen will place the public key in "~/.ssh/id_rsa.pub".
    """
    client = ControllerClient()
    with open(path, 'r') as source:
        key_string = source.read().strip()

    match = re.search("-----BEGIN \w+ PRIVATE KEY-----", key_string)
    if match is not None:
        print("The path ({}) contains a private key.".format(path))
        print("Please provide the path to your public key.")
        return None

    match = re.search("ssh-\S+ \S+ (\S+)", key_string)
    if match is not None:
        name = match.group(1)
    else:
        name = "{}@{}".format(getpass.getuser(), platform.node())

    result = client.add_ssh_key(key_string, name=name)
    if result is not None:
        print("Added public key from {}".format(path))

    return result 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:31,代码来源:cloud.py

示例14: write_geometry

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
def write_geometry(filepath, coords, faces, create_stamp=None):
    """Write a triangular format Freesurfer surface mesh.

    Parameters
    ----------
    filepath : str
        Path to surface file
    coords : numpy array
        nvtx x 3 array of vertex (x, y, z) coordinates
    faces : numpy array
        nfaces x 3 array of defining mesh triangles
    create_stamp : str
        User/time stamp (default: "created by <user> on <ctime>")
    """
    magic_bytes = np.array([255, 255, 254], dtype=np.uint8)

    if create_stamp is None:
        create_stamp = "created by %s on %s" % (getpass.getuser(),
            time.ctime())

    with open(filepath, 'wb') as fobj:
        magic_bytes.tofile(fobj)
        fobj.write("%s\n\n" % create_stamp)

        np.array([coords.shape[0], faces.shape[0]], dtype='>i4').tofile(fobj)

        # Coerce types, just to be safe
        coords.astype('>f4').reshape(-1).tofile(fobj)
        faces.astype('>i4').reshape(-1).tofile(fobj) 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:31,代码来源:io.py

示例15: test_geometry

# 需要导入模块: import getpass [as 别名]
# 或者: from getpass import getuser [as 别名]
def test_geometry():
    """Test IO of .surf"""
    surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "inflated"))
    coords, faces = read_geometry(surf_path)
    assert_equal(0, faces.min())
    assert_equal(coords.shape[0], faces.max() + 1)

    # Test quad with sphere
    surf_path = pjoin(data_path, "surf", "%s.%s" % ("lh", "sphere"))
    coords, faces = read_geometry(surf_path)
    assert_equal(0, faces.min())
    assert_equal(coords.shape[0], faces.max() + 1)

    # Test equivalence of freesurfer- and nibabel-generated triangular files
    # with respect to read_geometry()
    with InTemporaryDirectory():
        surf_path = 'test'
        create_stamp = "created by %s on %s" % (getpass.getuser(),
            time.ctime())
        write_geometry(surf_path, coords, faces, create_stamp)

        coords2, faces2 = read_geometry(surf_path)

        with open(surf_path, 'rb') as fobj:
            magic = np.fromfile(fobj, ">u1", 3)
            read_create_stamp = fobj.readline().rstrip('\n')

    assert_equal(create_stamp, read_create_stamp)

    np.testing.assert_array_equal(coords, coords2)
    np.testing.assert_array_equal(faces, faces2)

    # Validate byte ordering
    coords_swapped = coords.byteswap().newbyteorder()
    faces_swapped = faces.byteswap().newbyteorder()
    np.testing.assert_array_equal(coords_swapped, coords)
    np.testing.assert_array_equal(faces_swapped, faces) 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:39,代码来源:test_io.py


注:本文中的getpass.getuser方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。