Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP通过ssh执行shell命令_Php_Shell_Ssh - Fatal编程技术网

使用PHP通过ssh执行shell命令

使用PHP通过ssh执行shell命令,php,shell,ssh,Php,Shell,Ssh,我试图执行一个简单的shell命令,并在网页上打印结果,但结果是空的。下面是我找到的一段代码,但到目前为止还没有任何效果 <?php $server = "myserver"; $username = "myadmin"; $command = "ps"; $str = "ssh " .$username. "@" .$server. " " .$command; e

我试图执行一个简单的shell命令,并在网页上打印结果,但结果是空的。下面是我找到的一段代码,但到目前为止还没有任何效果

 <?php
            $server = "myserver";
            $username = "myadmin";
            $command = "ps";
            $str = "ssh " .$username. "@" .$server. " " .$command;

            exec($str, $output);

            echo '<pre>';
            print_r($output);
            echo '</pre>';
    ?>

试试看,行得通

$str = "ssh -p $port $username@$server $command";

端口号前缺少
-p
选项:

composer require phpseclib/phpseclib

使用更面向对象的解决方案,您可以通过以下方式安装版本2:

$ssh = new SSH2('yourhost');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}
然后只需创建ssh对象:

在这个示例中,我使用了通过用户名和密码的连接,但您也可以通过ssh密钥进行连接。
如果连接成功,您可以执行方法exec在服务器上执行您的命令。

ssh命令是否自行工作,这意味着您是否先在命令行中尝试过它?
exec($str,$output,$return)。还要检查错误代码,
var_dump(数组($output,$return))
echo$str获取字符串并尝试在shell中手动运行。@bjackfly是的,命令本身正在工作,但在script@Jigar没有错误代码,只是没有返回任何内容。我无法在这些机器上安装任何软件包。还有其他方法吗?好吧,如果你能在你的机器上创建PHP源文件,你可以安装phpseclib,因为那只是一堆PHP文件。是否可以使用SSH密钥而不是使用硬编码密码登录?很简单。查看他们的。使用SSH密钥也能很好地工作。
$ssh = new SSH2('yourhost');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}