python实现得到当前登录用户信息的方法

yipeiwu_com6年前Python基础

本文实例讲述了python实现得到当前登录用户信息的方法。分享给大家供大家参考,具体如下:

在linux 环境下,python 更多的被当做 替代 SHELL 的工具语言, 其实linux 中,本身就有很多命令是通过python扩展的,我想记录下一些常用的命令以及使用方式,以便以后查看.

第一部分:python得到得到当前登录用户信息

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

注意的是 pwd, grp 模块只能在linux,unix 下才有的. 我在网上搜索到了另一个在window 下得到用户组相关信息的方法,但需要安装  Python Win32 Extensions 模块。可以在这里下载 (http://starship.python.net/crew/mhammond/win32/),使用方法如下:

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"

得到用户名,当然只是第一步,后面还涉及到修改权限等操作。后面有时间再记录.

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

相关文章

python魔法方法-属性转换和类的表示详解

python魔法方法-属性转换和类的表示详解

类型转换魔法 类型转换魔法其实就是实现了str、int等工厂函数的结果,通常这些函数还有类型转换的功能,下面是一些相关的魔法方法: •__int__(self) •...

python实现图片上添加图片

python实现图片上添加图片

在介绍完给图上添加文字后,我们再介绍给图片上添加图片,也就是图片的叠加。 需要使用的Python的图像库:PIL.更加详细的知识点如下: Imaga模块:用来创建,打开,保存图片文件...

python遍历目录的方法小结

本文实例总结了python遍历目录的方法。分享给大家供大家参考,具体如下: 方法一使用递归: """ def WalkDir( dir, dir_callback = None, f...

在Python中分别打印列表中的每一个元素方法

Python版本 3.0以上 分别打印列表中的元素有两种: 方法一 a = [1,2,3,4] print(*a,sep = '\n') #结果 1 2 3 4 方法二 a...

解决在Python编辑器pycharm中程序run正常debug错误的问题

解决在Python编辑器pycharm中程序run正常debug错误的问题

初学Python,写了一小段程序,在pycharm中debug一直报错,在网上搜了很久,尝试多种方法后还是没有用。 尝试了很久之后,发现这个问题是由于: 1、程序中有中文注释。 2、程...