微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – 如何获得独特的`uid`?

我正在制作一个应该创建ftp用户的bash脚本.

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

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

解决方法:

获取用户的UID:

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

要向系统添加新用户,最好的选择是使用useradd或adduser(如果需要细粒度控件).

如果你真的只需要找到最小的免费UID,这里的脚本可以找到大于9​​99的最小空闲UID值(通常为系统用户保留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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐