用于获取Linux上已定义用户列表的Shell脚本?

Rob*_*ino 7 linux bash awk sed

我把它放在一起,但它很糟糕:(例如那里的魔术数字,文本解析..嘘!)

awk -F: '{if($3 >= 1000 && $3 < 2**16-2) print $1}' /etc/passwd
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?

Ste*_*ler 12

某些unix系统不使用/etc/passwd,或者没有在那里指定的用户.你应该使用getent passwd而不是阅读/etc/passwd.

我的系统还具有已禁用的用户,并且可以通过将其登录命令设置为/bin/false或更长时间登录/usr/sbin/nologin.您可能也想要排除它们.

这对我有用,包括arheops awk命令和ansgar的代码,以获得最小值和最大值login.defs:

getent passwd | \
grep -vE '(nologin|false)$' | \
awk -F: -v min=`awk '/^UID_MIN/ {print $2}' /etc/login.defs` \
-v max=`awk '/^UID_MAX/ {print $2}' /etc/login.defs` \
'{if(($3 >= min)&&($3 <= max)) print $1}' | \
sort -u
Run Code Online (Sandbox Code Playgroud)


mar*_*t1n 1

那么您只是想从 /etc/passwd 获取所有用户的列表?如果是这样,我相信这将是一个更简单的解决方案:

cut -d":" -f1 /etc/passwd
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您只需要用户定义的用户(而不是系统用户)的列表,您可以使用以下之一:

grep -E ":[0-9]{4,6}:[0-9]{4,6}:" /etc/passwd | cut -d: -f1
Run Code Online (Sandbox Code Playgroud)

^ 这假设您的系统对用户定义用户的 UID 和 GID 使用 1000 及以上

grep /home /etc/passwd | cut -d: -f1
Run Code Online (Sandbox Code Playgroud)

^ 这假设每个用户定义的用户都有一个主目录。

其他解决方案取决于更详细的标准和您的系统设置。