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

yipeiwu_com5年前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调用c++返回带成员指针的类指针实例

这个是OK的: class Rtmp_tool { public: int m_width; AVCodecContext * c; }; 指针的用法如下: Rtm...

Python 实现中值滤波、均值滤波的方法

Python 实现中值滤波、均值滤波的方法

红包: Lena椒盐噪声图片: # -*- coding: utf-8 -*- """ Created on Sat Oct 14 22:16:47 2017 @author:...

pytorch之inception_v3的实现案例

如下所示: from __future__ import print_function from __future__ import division import torch i...

Python基于sftp及rsa密匙实现远程拷贝文件的方法

本文实例讲述了Python基于sftp及rsa密匙实现远程拷贝文件的方法。分享给大家供大家参考,具体如下: 如果两台服务器之间使用了RSA秘钥免密码登录的方式,可以先查找出rsa秘钥的对...

Django中间件基础用法详解

前言 django的中间件可以在视图函数执行前执行,比如登陆验证、日志记录等,下面简单说明一下中间件的基础用法,主要为笔者学习时的笔记 1. 在django项目文件夹下创建一个用于存放中...