macintosh264
macintosh264

Reputation: 981

PHP-CLI Sudo Execution

I am running a cli-script, that requires a exec('sudo ...'); call. I know it is not safe on the web, but how can it be done in cli? The script is executed by a user known as "btcdbit", who is in the sudoers file.

Upvotes: 1

Views: 699

Answers (3)

nigol
nigol

Reputation: 286

In my experience setting the NOPASSWD option doesn't always work and even if it does it seems unsafe. Seems to me that a better approach - if you're able to use it - would involve using phpseclib to do sudo through SSH. eg.

<?php
include('Net/SSH2.php');

$sftp = new Net_SSH2('www.domain.tld');
$sftp->login('username', 'password');

echo $sftp->read('username@username:~$');
$sftp->write("sudo ls -la\n");
$output = $sftp->read('#Password:|username@username:~\$#', NET_SSH2_READ_REGEX);
echo $output;
if (preg_match('#Password:#', $lines)) {
    $ssh->write("password\n");
    echo $sftp->read('username@username:~$');
}
?>

The website "sudo in php" elaborates

Upvotes: 2

Jeff Day
Jeff Day

Reputation: 3717

It should be just as simple as exec('/usr/bin/sudo {script}').

Upvotes: -2

imm
imm

Reputation: 5919

So long as btcdbit is in sudoers for the program that you want it to be able to run, you should be able to use any of the PHP functions like exec or system to run it. Make sure that you use the NOPASSWD option in sudoers (see http://www.ducea.com/2006/06/18/linux-tips-password-usage-in-sudo-passwd-nopasswd/ for example) if you don't want it to get caught up asking btcdbit for a password.

Upvotes: 1

Related Questions