Mervyn
Mervyn

Reputation: 891

Execute a command using php under ssh2 in php

Using Mint terminal my script connects using ssh2_connect and ssh2_auth-password. When am logged in successfully I want to run a command which will give me the hardware cpu. Is there a way I can use to exec the command in my script then show the results. I have used system and exec for pinging. if i was in the terminal i do the login. then type "get hardware cpu"

in the terminal it would look like this:

Test~ $ get hardware cpu

Upvotes: 0

Views: 2001

Answers (3)

user1469439
user1469439

Reputation:

You could try this (requires phpseclib, a pure PHP SSH2 implementation):

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

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec("grep 'model name' /proc/cpuinfo");
?>

Upvotes: 1

steffen
steffen

Reputation: 17048

You need access to the shell:

$connection = ssh2_connect($ip, $port);
$stream = ssh2_shell($connection);
fputs($stream, $input);
$buffer = fread($stream, 8192);

Have a look at this example:

$input = "ls\nexit\n";
$connection = ssh2_connect($host, $port);
ssh2_auth_password($connection, $user, $pass);
$stream = ssh2_shell($connection);
stream_set_blocking($stream, 1);
stream_set_timeout($stream, 2);
fputs($stream, $input);

while (!feof($stream)) {
        echo $buffer = fread($stream, $buffersize);
}

You might have to sleep() and fread() manually since people experience problems when setting the ssh2 stream blocking.

Upvotes: 1

Marc B
Marc B

Reputation: 360872

I don't know where this "get hardware" command comes from. If you're trying to figure out what cpu is powering the system, then

grep 'model name' /proc/cpuinfo

will output the ID string of the cpu:

marc@panic:~$ grep 'model name' /proc/cpuinfo
model name      : Intel(R) Core(TM)2 CPU          6600  @ 2.40GHz
model name      : Intel(R) Core(TM)2 CPU          6600  @ 2.40GHz

Upvotes: 0

Related Questions