得到linux下用户名、id、shell(分别返回列表和字典)

来源:互联网 发布:ubuntu命令行删除文件 编辑:程序博客网 时间:2024/06/06 07:07

用笨办法实现(在python 2.4下可以用):

返回列表:

#! /usr/bin/env python#-*- coding:utf-8 -*-''' 概述:从/etc/passwd获取系统用户名、用户ID、shell,以列表形式返回输出:['root, 0, /bin/bash', 'bin, 1, /sbin/nologin', ...]Create data: 2012-02-09Version: 1.0Author: 沈涛'''import platformdef getUserName(UserType):    user_list = []        OSType = platform.system()        if (OSType == "Linux"):        fp = open('/etc/passwd').readlines()        for line in fp:            user_list = "%s, %s, %s" % (line.split('\n')[0].split(':')[0],                                   line.split('\n')[0].split(':')[2],                                   line.split('\n')[0].split(':')[6])                        elif (OSType == "Windows"):        print "Windows System"            return user_list


返回字典:

#! /usr/bin/env python#-*- coding:utf-8 -*-''' 概述:从/etc/passwd获取系统用户名、用户ID、shell,以字典形式返回输出:{'sync': ['5', '/bin/sync'], 'gg': ['506', '/bin/bash'], ...}Create data: 2012-02-09Version: 1.0Author: 沈涛'''import platformdef getUserName():    #user_list = {}    item = {}    OSType = platform.system()    print OSType    if (OSType == "Linux"):        fp = open('/etc/passwd').readlines()        for line in fp:            item1 = line.split('\n')[0].split(':')[0]            item2 = line.split('\n')[0].split(':')[2]            item3 = line.split('\n')[0].split(':')[6]            item[item1] = [item2, item3]    elif (OSType == "Windows"):        print "Windows System"    print itemif __name__ == "__main__":    getUserName()




原创粉丝点击