sudo in php

(with phpseclib)

By default, sudo caches passwords for 5 minutes after they've been entered. So while $ssh->read('Password:') will work the first time you try it, it won't work if you try it within five minutes after having initially ran it. The following code sample demonstrates how to get around this:

<?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:~$');
}
?>