我正在用 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/