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 读写文件,按行修改文件的方法

如下所示: >>> f = open(r'E:\python\somefile.txt','w') 打开文件,写模式 >>> f.write...

浅谈对pytroch中torch.autograd.backward的思考

反向传递法则是深度学习中最为重要的一部分,torch中的backward可以对计算图中的梯度进行计算和累积 这里通过一段程序来演示基本的backward操作以及需要注意的地方 >...

python中pygame安装过程(超级详细)

python中pygame安装过程(超级详细)

安装时是需要设置python环境变量的,下载python的时候底下有个小框框(没有默认选中) Add Python 3.7 to PATH需要选择的,如果没有选择的话,需要自己设置,我一...

python里使用正则的findall函数的实例详解

python里使用正则的findall函数的实例详解 在前面学习了正则的search()函数,这个函数可以找到一个匹配的字符串返回,但是想找到所有匹配的字符串返回,怎么办呢?其实得使用f...

Python 判断 有向图 是否有环的实例讲解

实例如下: import numpy from numpy import * def dfs( v ): vis[v] = -1 flag = 0 for i in range...