Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sudo with libssh2

Tags:

php

libssh2

<?php
$ssh = ssh2_connect('domain.tld'); 
ssh2_auth_password($ssh, 'username', 'password');

$shell = ssh2_shell($ssh);
echo fread($shell, 1024*1024);
fwrite($shell, "sudo ls -la\n");
$output = fread($shell, 1024*1024);
echo $output;
if (preg_match('#[pP]assword[^:]*:#', $output)) {
    fwrite($shell, "password\n");
    echo fread($shell, 1024*1024);
}

All that does is display the banner and prompt. It doesn't actually give me the output of the ls -la command. On phpseclib it works just fine.

Any ideas?


1 Answers

I wrote an SSH wrapper (https://github.com/bubba-h57/PHP-SSH2) to facilitate a lot of my own PHP scripting that needs to SSH into remote servers, and run into this issue quite often.

I solved it with this incantation:

echo <password> | sudo -S <command>

Which for you might look like:

fwrite($shell, "echo $mySudoPassword | sudo -S ls -la\n");

I just pipe the password everytime I use sudo, whether I think I need it or not.

Using my own wrapper, it looks like:

require_once 'SSH2.php';
// Test Unix
$username = 'someuser';
$password = 'somepwd';
$host = 'somenixhost.com';
$port = 22;
$ssh2 = new My_SSH2($host, $port);
$ssh2->authPassword( $username, $password);
$ssh2->setPrompt(':~#'); // Set initial expected prompt
$ssh2->openShell();
$ssh2->setPrompt("MYCUSTOMSSHPROMPT> "); // Create a unique, easily found prompt
$ssh2->exec("PS1='MYCUSTOMSSHPROMPT> '"); // Execute the command.
echo $ssh2->exec('cd /var/www') . "\n";   // Change directories.
echo $ssh2->exec("echo $password | sudo -S ls -la\n") . "\n"; // Print LS
echo "\n===================Begin History=============\n";
echo $ssh2->getHistory();
$ssh2->disconnect();
echo "\n===================end=============\n";
exit;
like image 190
bubba Avatar answered Mar 26 '26 19:03

bubba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!