code

사용자 존재 여부 확인

starcafe 2023. 5. 13. 10:28
반응형

사용자 존재 여부 확인

사용자가 존재하는지 확인하는 스크립트를 만들고 싶습니다.나는 아래의 논리를 사용하고 있습니다.

# getent passwd test > /dev/null 2&>1
# echo $?
0
# getent passwd test1 > /dev/null 2&>1
# echo $?
2

따라서 사용자가 존재한다면, 우리는 성공할 수 있습니다. 그렇지 않으면 사용자는 존재하지 않습니다.아래와 같이 bash 스크립트에 위의 명령어를 입력했습니다.

#!/bin/bash

getent passwd $1 > /dev/null 2&>1

if [ $? -eq 0 ]; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

제 스크립트는 항상 사용자가 존재한다고 말합니다.

# sh passwd.sh test
yes the user exists
# sh passwd.sh test1
yes the user exists
# sh passwd.sh test2
yes the user exists

위의 조건이 항상 TRUE로 평가되고 사용자가 존재한다고 말하는 이유는 무엇입니까?

제가 어디서 잘못되고 있나요?

업데이트:

모든 응답을 읽은 후, 저는 제 대본에서 문제를 발견했습니다.문제는 제가 리다이렉트하는 방식이었습니다.getent산출량.그래서 리다이렉션 같은 것들을 모두 제거하고,getent라인은 다음과 같습니다.

getent passwd $user  > /dev/null

이제 제 대본은 잘 작동하고 있습니다.

다음을 통해 사용자를 확인할 수도 있습니다.id지휘권

id -u name사용자의 합니다. 반환 값당를사의자해 ID")을 얻게 됩니다. 사용자가 존재하지 않으면 명령 반환 값($?)1

그리고 다른 대답들이 지적했듯이, 만약 당신이 원하는 것이 단지 사용자가 존재하는지 확인하는 것이라면,if와 함께idif이미 종료 코드를 확인합니다.현을 만지작거릴 필요가 없습니다.[,$?또는$():

if id "$1" &>/dev/null; then
    echo 'user found'
else
    echo 'user not found'
fi

없음)-u어쨌든 당신이 출력을 폐기하고 있기 때문입니다.

또한 이 스니펫을 함수나 스크립트로 변환할 경우 종료 코드도 적절하게 설정할 것을 제안합니다.

#!/bin/bash
user_exists(){ id "$1" &>/dev/null; } # silent, it just sets the exit code
if user_exists "$1"; code=$?; then  # use the function, save the code
    echo 'user found'
else
    echo 'user not found' >&2  # error messages should go to stderr
fi
exit $code  # set the exit code, ultimately the same set by `id`

종료 코드를 명시적으로 확인할 필요가 없습니다.해라

if getent passwd $1 > /dev/null 2>&1; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

만약 그것이 작동하지 않는다면, 당신의 것에 뭔가 문제가 있습니다.getent또는 사용자가 생각보다 많이 정의되어 있습니다.

간단히 사용하는 것이 어때요?

grep -c '^username:' /etc/passwd

사용자가 있으면 1(사용자가 최대 1개의 항목을 가지고 있으므로)을 반환하고 없으면 0을 반환합니다.

이것이 제가 결국 한 일입니다.Freeswitch 스크립트: bash 작크립트시:

# Check if user exists
if ! id -u $FS_USER > /dev/null 2>&1; then
    echo "The user does not exist; execute below commands to crate and try again:"
    echo "  root@sh1:~# adduser --home /usr/local/freeswitch/ --shell /bin/false --no-create-home --ingroup daemon --disabled-password --disabled-login $FS_USER"
    echo "  ..."
    echo "  root@sh1:~# chown freeswitch:daemon /usr/local/freeswitch/ -R"
    exit 1
fi

가장 간단한 해결책은 다음과 같습니다.

if id -u "$user" >/dev/null 2>&1; then
    echo 'user exists'
else
    echo 'user missing'
fi

>/dev/null 2>&1으로 단축할 수 있습니다.&>/dev/null사용자가 존재하지 않는지 여부만 확인하려는 경우:

if ! id -u "$user" >/dev/null 2>&1; then
    echo 'user missing'
fi

나는 id 명령어를 사용할 것을 제안합니다. 그것은 유효한 사용자 존재 wrt passwd 파일 엔트리를 테스트하기 때문입니다. 이것은 필요하지 않습니다. 같은 의미입니다.

if [ `id -u $USER_TO_CHECK 2>/dev/null || echo -1` -ge 0 ]; then 
echo FOUND
fi

참고: 0은 rootuid입니다.

저는 그것을 그런 식으로 사용했습니다.

if [ $(getent passwd $user) ] ; then
        echo user $user exists
else
        echo user $user doesn\'t exists
fi

Linux 사용자의 존재 여부를 확인하는 스크립트

스크립트 사용자의 존재 여부 확인

#! /bin/bash
USER_NAME=bakul
cat /etc/passwd | grep ${USER_NAME} >/dev/null 2>&1
if [ $? -eq 0 ] ; then
    echo "User Exists"
else
    echo "User Not Found"
fi

이 늦었지만 ㅠㅠㅠㅠㅠfinger에 대한 줍니다.

  sudo apt-get finger 
  finger "$username"

sed 사용:

username="alice"
if [ `sed -n "/^$username/p" /etc/passwd` ]
then
    echo "User [$username] already exists"
else
    echo "User [$username] doesn't exist"
fi

사실 저는 그 문제를 재현할 수 없습니다.$1이 비어 있는 경우를 제외하고 질문에 적힌 스크립트는 정상적으로 작동합니다.

그러나 스크립트에 의 리디렉션과 관련된 문제가 있습니다.stderr두 가지 형태가 있지만,&>그리고.>&존재, 사용하려는 경우>&이미 리디렉션했습니다.stdout그것이 그 형태인 것인 이유입니다.&>작동하지 않습니다.다음과 같은 방법으로 쉽게 확인할 수 있습니다.

getent /etc/passwd username >/dev/null 2&>1
ls

이름이 지정된 파일이 표시됩니다.1현재 디렉토리에 있습니다.사용할 항목2>&1대신 또는 다음을 사용합니다.

getent /etc/passwd username &>/dev/null

이것도 리디렉션됩니다.stdout그리고.stderr로./dev/null.

경고 리디렉션stderr로./dev/null좋은 생각이 아닐 수도 있어요일이 잘못되면 이유를 알 수 없게 됩니다.

사용자 정보는 /etc/passwd에 저장되므로 "grep 'username' /etc/passwd"를 사용하여 사용자 이름이 존재하는지 확인할 수 있습니다. 반면 "id" 셸 명령을 사용하면 사용자 ID와 그룹 ID가 인쇄되고, 사용자가 존재하지 않으면 "no sched user" 메시지가 인쇄됩니다.

셸 구현(예: Busybox vs. 성인)에 따라[연산자가 프로세스를 시작할 수 있음, 변경$?.

해라

getent passwd $1 > /dev/null 2&>1
RES=$?

if [ $RES -eq 0 ]; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

서버에 로그인합니다. grep "username" /etc/passwd가 있으면 사용자 세부 정보가 표시됩니다.

아래는 OS 배포를 확인하고 없으면 사용자를 생성하고 사용자가 있으면 아무것도 하지 않는 스크립트입니다.

#!/bin/bash

# Detecting OS Ditribution
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
elif type lsb_release >/dev/null 2>&1; then
OS=$(lsb_release -si)
elif [ -f /etc/lsb-release ]; then
    . /etc/lsb-release
    OS=$DISTRIB_ID
else
    OS=$(uname -s)
fi

 echo "$OS"

 user=$(cat /etc/passwd | egrep -e ansible | awk -F ":" '{ print $1}')

 #Adding User based on The OS Distribution
 if [[ $OS = *"Red Hat"* ]] || [[ $OS = *"Amazon Linux"* ]] || [[ $OS = *"CentOS"*  
]] && [[ "$user" != "ansible" ]];then
 sudo useradd ansible

elif [ "$OS" =  Ubuntu ] && [ "$user" != "ansible" ]; then
sudo adduser --disabled-password --gecos "" ansible
else
  echo "$user is already exist on $OS"
 exit
fi

시스템 사용자 생성some_user없는 경우에는

if [[ $(getent passwd some_user) = "" ]]; then
    sudo adduser --no-create-home --force-badname --disabled-login --disabled-password --system some_user
fi

나는 이 멋진 한 줄 솔루션이 좋습니다.

getent passwd username > /dev/null 2&>1 && echo yes || echo no

및 스크립트:

#!/bin/bash

if [ "$1" != "" ]; then
        getent passwd $1 > /dev/null 2&>1 && (echo yes; exit 0) || (echo no; exit 2)
else
        echo "missing username"
        exit -1
fi

사용:

[mrfish@yoda ~]$ ./u_exists.sh root
yes
[mrfish@yoda ~]$ echo $?
0

[mrfish@yoda ~]$ ./u_exists.sh
missing username
[mrfish@yoda ~]$ echo $?
255

[mrfish@yoda ~]$ ./u_exists.sh aaa
no
[mrfish@indegy ~]$ echo $?
2
echo "$PASSWORD" | su -c "cd /" "$USER"
if [ "$?" = "0" ];then
 echo "OK"
else
 echo "Error"
fi
#!/bin/bash
read -p "Enter your Login Name: " loginname
home=`grep -w $loginname /etc/passwd | cut -ef:6 -d:`
if [ $home ]
    echo "Exists"
else
    echo "Not Exist"
fi

언급URL : https://stackoverflow.com/questions/14810684/check-whether-a-user-exists

반응형