【问题标题】:Execute a command using php under ssh2 in php在php中ssh2下使用php执行命令
【发布时间】:2012-11-19 22:11:02
【问题描述】:

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

在终端中它看起来像这样:

测试~$获取硬件cpu

【问题讨论】:

标签: php ssh exec


【解决方案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 流阻塞时会遇到问题。

【讨论】:

  • 我已经尝试过在我完成 ssh2 身份验证后在终端中放入 get hardware cpu 时想要显示结果原因,它在终端中工作想要放置此命令并在我的 php 脚本中运行.
  • 这是我的脚本:
  • 资源 id#5 这是我在运行我的 php 文件时得到的
【解决方案2】:

你可以试试这个(需要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");
?>

【讨论】:

    【解决方案3】:

    我不知道这个“获取硬件”命令来自哪里。如果你想弄清楚是什么 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
    

    【讨论】:

    • 您需要通过 SSH 在终端上运行它 - 而不是通过 SCP。但你很幸运——如果你能做 SCP,这意味着你有 SSH 终端访问权限,因为 SCP 通过终端运行。
    猜你喜欢
    • 2020-07-25
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2012-08-18
    • 2018-10-06
    • 1970-01-01
    相关资源
    最近更新 更多