2010-09-06 90 views
2

我正在创建一个应该创建一个ftp用户的bash脚本。如何获得唯一的`uid`?

ftpasswd --passwd --file=/usr/local/etc/ftpd/passwd --name=$USER --uid=[xxx] 
    --home=/media/part1/ftp/users/$USER --shell=/bin/false 

唯一提供给脚本的参数是用户名。但ftpasswd也需要uid。我如何得到这个号码?有没有简单的方法来扫描passwd文件并获得最大数量,增加它并使用它?也许有可能从系统中获得这个数字?

+0

我想你会想用'useradd'或'adduser'。 'getent'和'id'也派上用场。 – 2010-09-06 08:42:07

回答

2

要获得用户的UID:

cat /etc/passwd | grep "^$usernamevariable:" | cut -d":" -f3 

要将新用户添加到系统中,最好的选择是使用useraddadduser,如果您需要af无粒度控制。

如果你真的只需要找到最小的自由UID,下面是找到的最小的自由UID值大于999的信息(UID 1-999通常保留给系统用户)的脚本:

#!/bin/bash 

# return 1 if the Uid is already used, else 0 
function usedUid() 
{ 
    if [ -z "$1" ] 
    then 
    return 
    fi 
    for i in ${lines[@]} ; do 
     if [ $i == $1 ] 
     then 
     return 1 
    fi 
    done 
return 0 
} 

i=0 

# load all the UIDs from /etc/passwd 
lines=($(cat /etc/passwd | cut -d: -f3 | sort -n)) 

testuid=999 

x=1 

# search for a free uid greater than 999 (default behaviour of adduser) 
while [ $x -eq 1 ] ; do 
    testuid=$(($testuid + 1)) 
    usedUid $testuid 
    x=$? 
done 

# print the just found free uid 
echo $testuid 
+1

总是通过“cmd <文件”来避免“cat file | cmd”。 您保存一个进程和多个数据副本。 如果cmd想要在它的标准输入中查找,那么使用cat变体就无法做到这一点。 如果你喜欢数据从左到右流动,请使用可能的(在大多数shell中):“ 2015-04-23 07:48:45

+0

@RaúlSalinas-Monteagudo你会介意粘贴更好的命令吗? – ffghfgh 2017-08-08 10:08:31

3

要获得UID给出一个用户名 “为myuser”:

cat /etc/passwd | grep myuser | cut -d":" -f3 

要获得passwd文件的最大UID:

cat /etc/passwd | cut -d":" -f3 | sort -n | tail -1 
+0

我喜欢最后一种方法;然而,很多时候'/ etc/passwd'会有一个UID 65534('nfsnobody')的入口。这需要绕过如下:'grep -v':65534:'/ etc/passwd | cut -d:-f3 | sort -n | tail -1' – sxc731 2017-02-07 15:18:50

4

相反阅读/etc/passwd,你也可以做一个更nsswitch的友好的方式:

getent passwd 

另外不要忘记,没有任何保证的UID的这个序列将已经排序。

1

我将猫猫/etc/passwd更改为getent passwd给Giuseppe的回答。

#!/bin/bash 
# From Stack Over Flow 
# http://stackoverflow.com/questions/3649760/how-to-get-unique-uid 
# return 1 if the Uid is already used, else 0 
function usedUid() 
{ 
    if [ -z "$1" ] 
    then 
    return 
    fi 
    for i in ${lines[@]} ; do 
     if [ $i == $1 ] 
     then 
     return 1 
    fi 
    done 
return 0 
} 

i=0 

# load all the UIDs from /etc/passwd 
lines=($(getent passwd | cut -d: -f3 | sort -n)) 
testuid=999 

x=1 

# search for a free uid greater than 999 (default behaviour of adduser) 
while [ $x -eq 1 ] ; do 
    testuid=$(($testuid + 1)) 
    usedUid $testuid 
    x=$? 
done 

# print the just found free uid 
echo $testuid 
0

这是一个非常短的方法:

#!/bin/bash 
uids=$(cat /etc/passwd | cut -d: -f3 | sort -n) 
uid=999 

while true; do 
    if ! echo $uids | grep -F -q -w "$uid"; then 
     break; 
    fi 

    uid=$(($uid + 1)) 
done 

echo $uid