简体   繁体   English

使用Python创建Linux用户列表

[英]Creating a Linux Userlist with Python

I am writing a script in Python that will look at all of the groups AND all of the users on a linux system, and output me a file. 我正在用Python编写一个脚本,该脚本将查看Linux系统上的所有组和所有用户,并向我输出文件。

I have a situation where if an account is in a certain group, I want to set the user ID myself (in this example, it is because the account/s is a Non User Account) 我遇到一种情况,如果某个帐户在某个组中,则我想自己设置用户ID(在此示例中,因为该帐户是非用户帐户)

Code below: 代码如下:

#/usr/bin/python
import grp,pwd,os
from os.path import expanduser


destdir = expanduser("~")
destfile = '/newfile.txt'
appname = 'app name'
groupid = ''
userid = ''

#delete old feed file and create file
if os.path.exists(destdir + destfile):
        os.remove(destdir + destfile)
        print "file deleted...creating new file"
        output = open(destdir + destfile, 'w+')
        output.write('ACCOUNTID|USERLINKID|APPLICATIONROLE|APPLICATION' + '\n')
else:
        print "no file to delete...creating file"
        output = open(destdir + destfile, 'w+')
        output.write('ACCOUNTID|USERLINKID|APPLICATIONROLE|APPLICATION' + '\n')


#get user/group data for all users non primary groups
#documentation: https://docs.python.org/2/library/grp.html
groups = grp.getgrall()
for group in groups:
    groupid = group[2]
    print groupid #checking to see if group ids print correctly. Yes it does
    for user in group[3]:
        if groupid == '33': #Issue is here!
                userid = 'qwerty'
                print userid #testing var
                output.write(user + '|' + userid + '|' + group[0] + '|' + appname + '\n')

The issue is here: 问题在这里:

if groupid == '33': #Issue is here!
                userid = 'qwerty'
                print userid #testing var

The variable "userid" is never set to it's value and never prints anything while testing. 从未将变量“ userid”设置为其值,并且在测试期间从不打印任何内容。

The group "33" does have users in it and exists. 组“ 33”中确实有用户并且存在。 I cannot figure out why this doesn't work :( 我不知道为什么这不起作用:(

I have another piece of code that does this for users (as I am looking at both Primary and Secondary groups, and once I figure out this part, I can fix the rest) 我还有另一段代码可以为用户执行此操作(因为我正在查看主要和次要组,一旦弄清楚了这部分,就可以修复其余部分)

您的groupid验证是针对字符串的,它是整数

if groupid == 31: # then do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM