Ben Chuanlong Du's Blog

And let it direct your passion with reason.

Get User's Information in Python

In [1]:
import os
import getpass

getpass.getuser

In [2]:
getpass.getuser()
Out[2]:
'dclong'

getpass.getpass

Prompt the user for a password without echoing. This is a secure way of asking user for password in a Python script.

In [ ]:
getpass.getpass()

os.getuid

In [3]:
os.getuid()
Out[3]:
1000

os.getgid

In [4]:
os.getgid()
Out[4]:
1000

os.geteuid

In [5]:
os.geteuid()
Out[5]:
1000

os.getegid

In [6]:
os.getegid()
Out[6]:
1000

os.getresuid

In [7]:
os.getresuid()
Out[7]:
(1000, 1000, 1000)

os.getresgid

In [8]:
os.getresgid()
Out[8]:
(1000, 1000, 1000)

pwd

You can use the pwd module to get the user ID and group ID of any user.

In [1]:
import pwd
In [2]:
pwd.getpwnam("dclong")
Out[2]:
pwd.struct_passwd(pw_name='dclong', pw_passwd='x', pw_uid=501, pw_gid=20, pw_gecos='dclong', pw_dir='/home/dclong', pw_shell='/bin/bash')
In [5]:
pwd.getpwnam("dclong").pw_gid
Out[5]:
20
In [4]:
pwd.getpwuid(501)
Out[4]:
pwd.struct_passwd(pw_name='dclong', pw_passwd='x', pw_uid=501, pw_gid=20, pw_gecos='dclong', pw_dir='/home/dclong', pw_shell='/bin/bash')
In [6]:
pwd.getpwuid(501).pw_gid
Out[6]:
20

Test User's Access to Path

In [7]:
os.access("/home", os.R_OK)
Out[7]:
True
In [8]:
os.access("/home", os.W_OK)
Out[8]:
False
In [6]:
!ls -lha /home
total 12K
drwxr-xr-x  1 root   root   4.0K Jun 28 18:12 .
drwxr-xr-x  1 root   root   4.0K Jun 28 18:12 ..
drwxr-x--- 12 dclong docker 4.0K Jul  5 17:25 dclong
In [9]:
os.access("/tmp", os.W_OK)
Out[9]:
True
In [ ]:
 

Comments