在php中的ssh2下使用php执行命令

时间:2012-11-15 14:54:21

标签: php ssh exec

使用Mint终端,我的脚本使用ssh2_connect和ssh2_auth-password连接。 当我成功登录时,我想运行一个命令,它将给我硬件CPU。有没有办法可以用来在我的脚本中执行命令然后显示结果。我使用system和exec进行ping操作。如果我在终端我登录。然后输入“get hardware cpu”

终端中的

看起来像这样:

测试〜$ get hardware cpu

3 个答案:

答案 0 :(得分:1)

您需要访问shell:

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

看一下这个例子:

$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);
}

您可能必须手动sleep()fread(),因为在设置ssh2流阻塞时遇到问题。

答案 1 :(得分:1)

您可以尝试此操作(需要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");
?>

答案 2 :(得分:0)

我不知道这个“获取硬件”命令来自哪里。如果你想弄清楚什么CPU正在为系统供电,那么

grep 'model name' /proc/cpuinfo

将输出cpu的ID字符串:

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
相关问题