如何在linux pc中使用php中的shell脚本添加用户


How to add user in linux pc using shell script in php

我试图将用户添加到我的LAN pc(ubuntu 14.04)中,但失败了。举个例子:

mypc:192.168.0.11serverpc:192.168.0.100

我可以用shell脚本将用户创建到"mypc"中。但当我尝试连接并将用户添加到"serverpc"时:返回"添加用户失败!"。我使用的是PHP:

这是我的方法:

public function test_ldap(){
    $username = escapeshellarg('different');
    $password = escapeshellarg('different');
    #$udomain = 'edutechsolutionsbd.com';
    $u_domain = '192.168.0.100';
    $u_user = 'etsb';
    $output = exec("sudo shell_script/add_user.sh $username $password $u_domain $u_user 2>&1");
    #$output = shell_exec("/usr/bin/php -v");
    print_r($output);
    exit;
}

shell脚本::

#!/bin/bash
# Script to add a user to Linux system
# -------------------------------------------------------------------------
# Copyright (c) 2007 nixCraft project <http://bash.cyberciti.biz/>
# This script is licensed under GNU GPL version 2.0 or above
# Comment/suggestion: <vivek at nixCraft DOT com>
# -------------------------------------------------------------------------
# See url for more info:
# http://www.cyberciti.biz/tips/howto-write-shell-script-to-add-user.html
# -------------------------------------------------------------------------
if [ $(id -u) -eq 0 ]; then
username=$1
password=$2
u_domain=$3
u_user=$4
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
    echo "$username exists!"
    exit 1
else
    pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
    #useradd -m -p $pass $username
    sudo ssh $u_user@$u_domain "useradd -m -p $pass $username"
    [ $? -eq 0 ] && echo "User is Created Successfully!" || echo     "Failed to add a user!"
fi
else
echo "Only root may add a user to the system"
exit 2
 fi

我的问题是:如何在ubuntu中的另一台电脑中创建用户?提前感谢。

根据我的经验,PHP的exec()函数不支持运行带有sudo提升权限标志的任务。我将www-data用户(即web服务器应该在其下运行的用户)添加到使用命令sudo visudo -f /etc/sudoers在机器上打开的/etc/sudoers文件中,然后在该行includedir /etc/sudoers.d user_name ALL=(ALL)下方。

然后我添加了以下行。。。

www-data ALL=(ALL) NOPASSWD: ALL

基本上,您要做的是将www数据用户添加到sudoers列表中,并允许它访问sudo命令并在提升的权限下运行。

然而,我应该注意到,这是一个非常危险的更改,因为这意味着任何人都可以使用网络服务器的用户访问提升的权限,如果这是一台面向公众的服务器,这将带来巨大的风险,因此使用时要格外小心。