bash 脚本 returns 该用户存在但用户不存在

bash script returns that user exists but user does not exist

请注意代码中 FI 后的备注! 为了通过浏览器创建用户帐户,我让 php shell_exec 执行 bash 脚本。尽管我确定(通过检查 /etc/shadow)用户名没有被占用,但脚本说确实如此。 现在的脚本执行 useradd 命令,用户名出现在 /etc/shadow 中。 貌似之前执行了useradd然后检查用户是否存在?

php

$command = "sudo ./createclientcert.sh $userName $userPass";
if(shell_exec("$command echo $?") == 0){
echo 1;
}

Shellscript

#!/bin/bash

newclient () {
getent passwd  > /dev/null 2&>1
if [ $? -eq 0 ]; then
echo $?
else
useradd 
echo : | chpasswd   
fi
# PLEASE TAKE NOTE!! funny thing is that when code (that had nothing to do with the account creation and was to be removed) that came after fi is in place it works well. 
}

newclient "" ""

当你在系统上 运行 输出什么?

getent passwd [username]

此用户的记录可能存在于以下位置之一,因为 getent 搜索这些位置,而不仅仅是 /etc/shadow:

The databases it searches in are: ahosts, ahostsv4, ahostsv6, aliases, ethers (Ethernet addresses), group, gshadow, hosts, netgroup, networks, passwd, protocols, rpc, services, and shadow.

来源:https://en.wikipedia.org/wiki/Getent

尝试删除用户:

userdel -r [username]

其中 -r 将删除用户的所有文件以及用户本身。 之后再次尝试 运行ning PHP 脚本。

不是真正的答案,但它可以保留愚蠢的 7z。比扎尔!!

#!/bin/bash

newclient () {
getent passwd  >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo $?
else
useradd -p encrypted_password 
#useradd 
echo : | chpasswd   
fi
# if i remove the following line or comment it out the script starts  malfunctioning
7z a /var/www/html/download/.zip /var/www/html/download/.ovpn 
}

newclient "" ""

尝试这样的事情:

#!/bin/bash

if useradd "" >/dev/null ; then
    echo : | chpasswd >/dev/null
    # user created
    exitcode=0
else
    # user already exists
    exitcode=1
fi

# do stuff regardless if user created or not
7z a /var/www/html/download/.zip /var/www/html/download/.ovpn

# the script would exit with the exit code of latest executed command
# if you dont explicitly give another exit code:
exit $exitcode

PHP

$output = system("sudo ./createclientcert.sh \"$userName\" \"$userPass\"", $exitcode);

switch($exitcode)
{
  case 0:
    echo "User created."
    break;
  case 1:
    echo "User already exists.";
    break;
}