bash脚本返回该用户存在但用户不存在

时间:2016-12-12 05:06:25

标签: php bash shell-exec

请注意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;
}

的shell

#!/bin/bash

newclient () {
getent passwd $1 > /dev/null 2&>1
if [ $? -eq 0 ]; then
echo $?
else
useradd $1
echo $1:$2 | 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 "$1" "$2"

3 个答案:

答案 0 :(得分:0)

在系统上运行时的输出是什么?

getent passwd [username]

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

  

它搜索的数据库是:ahosts,ahostsv4,ahostsv6,别名,ethers(以太网地址),group,gshadow,hosts,netgroup,networks,passwd,protocols,rpc,services和shadow。

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

尝试删除用户:

userdel -r [username]

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

答案 1 :(得分:0)

不是真正的答案,但它可以让愚蠢的7z到位。 Bizar !!

#!/bin/bash

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

newclient "$1" "$2"

答案 2 :(得分:0)

尝试这样的事情:

#!/bin/bash

if useradd "$1" >/dev/null ; then
    echo $1:$2 | 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/$1.zip /var/www/html/download/$1.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;
}