本文整理汇总了Python中pwd.getpwuid方法的典型用法代码示例。如果您正苦于以下问题:Python pwd.getpwuid方法的具体用法?Python pwd.getpwuid怎么用?Python pwd.getpwuid使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pwd
的用法示例。
在下文中一共展示了pwd.getpwuid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: netstat_tcp6
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def netstat_tcp6():
'''
This function returns a list of tcp connections utilizing ipv6. Please note that in order to return the pid of of a
network process running on the system, this script must be ran as root.
'''
tcpcontent = _tcp6load()
tcpresult = []
for line in tcpcontent:
line_array = _remove_empty(line.split(' '))
l_host, l_port = _convert_ipv6_port(line_array[1])
r_host, r_port = _convert_ipv6_port(line_array[2])
tcp_id = line_array[0]
state = TCP_STATE[line_array[3]]
uid = pwd.getpwuid(int(line_array[7]))[0]
inode = line_array[9]
pid = _get_pid_of_inode(inode)
try: # try read the process name.
exe = os.readlink('/proc/' + pid + '/exe')
except:
exe = None
nline = [tcp_id, uid, l_host + ':' + l_port,
r_host + ':' + r_port, state, pid, exe]
tcpresult.append(nline)
return tcpresult
示例2: getuser
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def getuser():
sysuser = os.getenv("USER")
# if sysuser could not be identified try Logname
if sysuser == None:
print("Getuser: Running from crontab -- trying Logname to identify user")
try:
sysuser = os.getenv("LOGNAME").replace("LOGNAME=", "")
except:
sysuser = None
if not sysuser == None:
print("Getuser: ... succes - using", sysuser)
# if sysuser still could not be identified assume that uid 1000 is the defaultuser (on linux)
if sysuser == None or sysuser == 'None':
print("Getuser: Cannot identify user by standard procedures - switching to default uid 1000")
sysuser = pwd.getpwuid(1000)[0]
print("Getuser: now using", sysuser)
return sysuser
# path to home directory
#if os.isatty(sys.stdin.fileno()):
# sysuser = os.getenv("USER")
# pass
#else:
# sysuser = os.getenv("LOGNAME").replace("LOGNAME=", "")
# pass
示例3: getuser
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def getuser():
"""Function to get the username from the environment or password database.
First try various environment variables, then the password
database. This works on Windows as long as USERNAME is set.
"""
# this is copied from the oroginal getpass.py
import os
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
return user
# If this fails, the exception will "explain" why
import pwd
return pwd.getpwuid(os.getuid())[0]
示例4: shell_lookup
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def shell_lookup():
"""Find an appropriate shell for the user"""
try:
usershell = pwd.getpwuid(os.getuid())[6]
except KeyError:
usershell = None
shells = [usershell, 'bash', 'zsh', 'tcsh', 'ksh', 'csh', 'sh']
for shell in shells:
if shell is None:
continue
elif os.path.isfile(shell):
return(shell)
else:
rshell = path_lookup(shell)
if rshell is not None:
dbg('shell_lookup: Found %s at %s' % (shell, rshell))
return(rshell)
dbg('shell_lookup: Unable to locate a shell')
示例5: from_uid
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def from_uid(cls, uid):
result = cls()
# Only available on Linux.
try:
import pwd
record = pwd.getpwuid(uid)
result.uid = uid
result.username = record.pw_name
result.homedir = record.pw_dir
result.shell = record.pw_shell
except (KeyError, ImportError):
pass
return result
示例6: open_file
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def open_file(s):
with open(s,'r') as f:
f.next()
f.next()
f.next()
for line in f:
if "FOUND" in line:
x = line.split(':')
file_paths.append(x[0])
if len(file_paths) == 0:
print {}
return
for p in file_paths:
filename = p
get_time = os.path.getctime(p)
format_time = datetime.fromtimestamp(get_time).strftime('%Y-%m-%d %H:%M:%S')
hashvalue = hashlib.sha1(filename).hexdigest()
owner_name = getpwuid(stat(filename).st_uid).pw_name
json_output["malicious_files"].append({"file":p, "owner":owner_name, "hash_value":hashvalue, "time_created":format_time})
print json.dumps(json_output)
# Scan the directory
示例7: username
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def username(self):
"""
str: Some services require authentication in order to connect to the
service, in which case the appropriate username can be specified. If not
specified at instantiation, your local login name will be used. If `True`
was provided, you will be prompted to type your username at runtime as
necessary. If `False` was provided, then `None` will be returned. You can
specify a different username at runtime using: `duct.username = '<username>'`.
"""
if self._username is True:
if 'username' not in self.__cached_auth:
self.__cached_auth['username'] = input("Enter username for '{}':".format(self.name))
return self.__cached_auth['username']
elif self._username is False:
return None
elif not self._username:
try:
username = os.getlogin()
except OSError:
username = pwd.getpwuid(os.geteuid()).pw_name
return username
return self._username
示例8: pcocc_run
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def pcocc_run(jobid, jobname, user, indices, script, mirror_env, cmd, timeout, cluster):
#FIXME: handle pty option once we have agent support
vms = CLIRangeSet(indices, cluster)
if not user:
user = pwd.getpwuid(os.getuid()).pw_name
cmd = list(cmd)
if script:
basename = os.path.basename(cmd[0])
dest = os.path.join('/tmp', basename)
writefile(cluster, vms, cmd[0], dest, timeout)
cmd = ['bash', dest]
env = []
if mirror_env:
for e, v in os.environ.iteritems():
env.append("{}={}".format(e,v))
exit_code = multiprocess_call(cluster, vms, cmd, env, user, timeout)
sys.exit(exit_code)
示例9: get_default_dotm2ee_directory
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def get_default_dotm2ee_directory(self):
dotm2ee = os.path.join(pwd.getpwuid(os.getuid())[5], ".m2ee")
if not os.path.isdir(dotm2ee):
try:
os.mkdir(dotm2ee)
except OSError as e:
logger.debug("Got %s: %s" % (type(e), e))
import traceback
logger.debug(traceback.format_exc())
logger.critical(
"Directory %s does not exist, and cannot be " "created!"
)
logger.critical(
"If you do not want to use .m2ee in your home "
"directory, you have to specify pidfile, "
"munin -> config_cache in your configuration "
"file"
)
sys.exit(1)
return dotm2ee
示例10: check_for_writable_imgdir
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def check_for_writable_imgdir():
c.debug("Testing write perms by creating tempfile in {}".format(cfg.opts.img_dir))
try:
f = tempfile.TemporaryFile(dir=cfg.opts.img_dir)
f.close()
except:
dirstat = os.stat(cfg.opts.img_dir)
user = pwd.getpwuid(dirstat.st_uid).pw_name
group = grp.getgrgid(dirstat.st_gid).gr_name
print(c.RED("Unable to create new file in image dir '{}' owned by {}:{}".format(cfg.opts.img_dir, user, group)))
if myUser in grp.getgrnam(group).gr_mem:
print("Your user ({}) *is* a member of the appropriate group ({}); however ...\n"
"Your current login session is not running with that group credential\n"
"To fix this, open a new session (ssh/su -) or log out & log back in (GUI)".format(myUser, group))
else:
print("Either fix directory permissions as root or specify alternate dir with '--img-dir' option")
exit(1)
示例11: check_environ
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def check_environ ():
"""Ensure that 'os.environ' has all the environment variables we
guarantee that users can use in config files, command-line options,
etc. Currently this includes:
HOME - user's home directory (Unix only)
PLAT - description of the current platform, including hardware
and OS (see 'get_platform()')
"""
global _environ_checked
if _environ_checked:
return
if os.name == 'posix' and 'HOME' not in os.environ:
import pwd
os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
if 'PLAT' not in os.environ:
os.environ['PLAT'] = get_platform()
_environ_checked = 1
示例12: _find_grail_rc
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def _find_grail_rc(self):
import glob
import pwd
import socket
import tempfile
tempdir = os.path.join(tempfile.gettempdir(),
".grail-unix")
user = pwd.getpwuid(os.getuid())[0]
filename = os.path.join(tempdir, user + "-*")
maybes = glob.glob(filename)
if not maybes:
return None
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
for fn in maybes:
# need to PING each one until we find one that's live
try:
s.connect(fn)
except socket.error:
# no good; attempt to clean it out, but don't fail:
try:
os.unlink(fn)
except IOError:
pass
else:
return s
示例13: getuser
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def getuser():
"""Get the username from the environment or password database.
First try various environment variables, then the password
database. This works on Windows as long as USERNAME is set.
"""
import os
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
return user
# If this fails, the exception will "explain" why
import pwd
return pwd.getpwuid(os.getuid())[0]
# Bind the name getpass to the appropriate function
示例14: check_environ
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def check_environ ():
"""Ensure that 'os.environ' has all the environment variables we
guarantee that users can use in config files, command-line options,
etc. Currently this includes:
HOME - user's home directory (Unix only)
PLAT - description of the current platform, including hardware
and OS (see 'get_platform()')
"""
global _environ_checked
if _environ_checked:
return
if os.name == 'posix' and 'HOME' not in os.environ:
try:
import pwd
os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
except (ImportError, KeyError):
# bpo-10496: if the current user identifier doesn't exist in the
# password database, do nothing
pass
if 'PLAT' not in os.environ:
os.environ['PLAT'] = get_platform()
_environ_checked = 1
示例15: test_check_environ_getpwuid
# 需要导入模块: import pwd [as 别名]
# 或者: from pwd import getpwuid [as 别名]
def test_check_environ_getpwuid(self):
util._environ_checked = 0
os.environ.pop('HOME', None)
import pwd
# only set pw_dir field, other fields are not used
def mock_getpwuid(uid):
return pwd.struct_passwd((None, None, None, None, None,
'/home/distutils', None))
with swap_attr(pwd, 'getpwuid', mock_getpwuid):
check_environ()
self.assertEqual(os.environ['HOME'], '/home/distutils')
util._environ_checked = 0
os.environ.pop('HOME', None)
# bpo-10496: Catch pwd.getpwuid() error
def getpwuid_err(uid):
raise KeyError
with swap_attr(pwd, 'getpwuid', getpwuid_err):
check_environ()
self.assertNotIn('HOME', os.environ)