python - 使用 Python 创建 Linux 用户列表

标签 python linux unix

我正在用 Python 编写一个脚本,它将查看 Linux 系统上的所有组和所有用户,并向我输出一个文件。

我有一种情况,如果一个帐户在某个组中,我想自己设置用户 ID(在本例中,这是因为该帐户是非用户帐户)

代码如下:

#/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')

问题在这里:

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

变量“userid”从未设置为其值,并且在测试时从未打印任何内容。

组“33”确实有用户并且存在。我不明白为什么这不起作用:(

我有另一段代码可以为用户执行此操作(因为我正在查看主要组和次要组,一旦我弄清楚这部分,我就可以修复其余部分)

最佳答案

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

if groupid == 31: # then do something

关于python - 使用 Python 创建 Linux 用户列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29535083/

相关文章:

Python 目录等同于 perl?

python - 在大型 Python 代码库中从结果追溯到原因

linux - 如何从日期格式的目录列表中复制最新目录

linux - Linux中的fork()是否将父进程的所有内存页复制到子进程?

c - 使用管道同步兄弟进程

python - 更改DataFrame中某行的增量值

python - 将数据帧拆分为多个 5 秒数据帧并在 Python 中获取计数

linux - 如何静态链接 libexpat.so.1 与 GCC?

Linux 进程状态

Linux - 处理进程终止