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中利用GDAL对tif文件进行读写的方法

利用GDAL库对tif影像进行读取 示例代码默认波段为[B、G、R、NIR的顺序,且为四个波段] import gdal def readTif(fileName): datas...

优化Python代码使其加快作用域内的查找

我将示范微优化(micro optimization)如何提升python代码5%的执行速度。5%!同时也会触怒任何维护你代码的人。 但实际上,这篇文章只是解释一下你偶尔会在标准库或者其...

Python及Pycharm安装方法图文教程

Python及Pycharm安装方法图文教程

Python及Pycharm安装方法,供大家参考,具体内容如下 1、任务简介 为了学习Python我今天对它进行了安装,整个安装过程忘了截图,故我在虚拟机中重新安装了一遍,并将Pytho...

使用python实现生成用户信息

今天练习的时候要展示一个从用户信息列表,就想把他做成信息和修改在一起的一个网页,方便用户修改内容 考虑到要把信息和值分开放,那么肯定是字典了,因为需要保证位置不变,使用有序字典 考虑到需...

对python中dict和json的区别详解

1、json 和 字典 区别 >>>import json >>>json.dumps({1:2}) >>>'{"1":2}...