python implements the method of getting current logged in user information

  • 2021-06-29 11:25:49
  • OfStack

This article provides an example of how python implements getting information about the currently logged-in user.Share it for your reference, as follows:

In the linux environment, python is more used as a tool language to replace SHELL. In fact, there are many commands extended by python in linux itself. I want to record some commonly used commands and how to use them for later review.

Part 1: python gets information about the currently logged in user


def get_current_user():
  try:
    # pwd is unix only
    import pwd 
    return pwd.getpwuid(os.getuid())[0]
  except ImportError, e:  
    import getpass
    return getpass.getuser()
def get_default_group_for_user(user):
  import grp
  group = None
  try:
    gid= pwd.getpwnam(user)[3]
    groups = grp.getgrgid(gid)[0]
  except KeyError, e:
    print( 'Failed to find primary group from user %s' ,user)
    return group

Note that pwd, grp modules are available only under linux and unix. I searched the Internet for another way to get information about user groups under window, but I need to install the Python Win32 Extensions module.You can download it here (http://starship.python.net/crew/mhammond/win32/) using the following methods:


import win32net
import platform
import getpass
#Get current hostname and username
sHostname = platform.uname()[1]
sUsername = getpass.getuser()
#Define account memberships to test as false
memberAdmin = False
memberORA_DBA = False
for groups in win32net.NetUserGetLocalGroups(sHostname,sUsername):
  #If membership present, set to true
  if groups == 'Administrators':
    print "member of admin"
    memberAdmin = True
  if groups == 'ORA_DBA':
    print "member of orA_DBA"
    memberORA_DBA = True
#if all true pass, else fail
if (memberAdmin == True) and (memberORA_DBA == True):
  print "membership is good"
else:
  print "current account does not have the proper group membership"

Getting the user name is, of course, the first step, followed by actions such as modifying permissions.You have time to record later.

We hope that the description in this paper will be helpful to everyone's Python program design based on the Django framework.


Related articles: