2

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;
2

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

12 Comments

I tried it but unfortunately its not working. Anything I am missing out on?
@curious_coder Sorry, I forgot the echo statement, which means the shell tried to execute the string. I've added the echo statement and tested it.
I tried it but I am unable to get it to work. The password remains unchanged. I have added update to the question
Do we need to add sudo?
@curious_coder Ah, yes, you need to have permission to actually execute the statement. Using sudo should fix your issue. I'll add some debugging to the script, too.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.