在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"

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