2010-09-06 37 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