curious_coder
curious_coder

Reputation: 2468

Php script to change Ubuntu user password

I have written a php script to allow users to create accounts for mailing service.

shell_exec("sudo useradd -m ".escapeshellcmd($user_name)." -s /sbin/nologin"." -p ".crypt(escapeshellcmd($user_password),"abcd"));

Now I would like to allow users to change/delete their password/account. I tried using

shell_exec("sudo deluser --remove-all-files -f ".$username);

I have no idea how to implement password changing.

Unfortunately the commands doesn't seem to be working. How can I implement these?

Update: Piece of code to handle password change

case 'change':
  $username = $_POST['value'];
  $newpwd = $_POST['Pwd'];

  // Berry Langerak's code
  $out = shell_exec(
       sprintf(
         "echo '%s:%s' | chpasswd", 
          escapeshellarg($username), 
          escapeshellarg($newpwd)
        )
      );
echo(json_encode($username." password has been updated"));
break;

Upvotes: 2

Views: 1585

Answers (1)

Berry Langerak
Berry Langerak

Reputation: 18859

Well, in Ubuntu, the command for changing the password of a regular user would be:

passwd $username

But then, the shell is interactive, which might be very annoying for a PHP script. There's a non-interactive alternative though:

echo '$username:$password' | sudo chpasswd

In your PHP script, you could do this:

<?php
$username = 'foo';
$password = 'foo';

$command = sprintf(
    "echo '%s:%s' | sudo chpasswd", 
    escapeshellarg($username), 
    escapeshellarg($password)
);

exec($command, $output, $return);

if ($return === 0) {
   // success.
}
else {
   var_dump($return, $output); // failure.
}

DISCLAIMER: when you're executing this line, do be aware that this command will be visible in .bash_history, and in the process list. You might want to encrypt the password before executing your shell command, and send the -e flag to chpasswd, to mitigate these risks.

EDIT: Forgot the echo statement, added it.

EDIT: Added some debugging to the script.

Upvotes: 3

Related Questions