【问题标题】:Having trouble with PHP-SSH2 connecting to remote serverPHP-SSH2 连接到远程服务器时遇到问题
【发布时间】:2019-11-19 23:11:03
【问题描述】:

我正在尝试编写我的第一个 PHP 脚本,但我很挣扎,主要问题是连接/执行部分无法正常工作,而是抛出“无法连接到服务器”消息...

尝试更改代码 if 语句。

<?php
  include('Net/SSH2.php');
  //Coded by Aaron Akhtar
  //May not be the best code, this is my first ever php script ;P

  //edit the information below to match your ssh details or this will not work!
  $address = "104.xxx.xx.xx";
  $user = "root"; //do not change unless you are using another user from root
  $password = "xxxxx";

  $command = $_GET["command"];

  if(empty($command)){
    echo "Please specify a command to send to the server...";
    die();
  }

    function execute(){
    $connection = ssh2_connect($address, 22);
    if(ssh2_auth_password($connection, $user, $password)){
      echo ssh2_exec($connection, $command);
    }else {
      die("Could not connect to server...");
    }

  }

  execute();

 ?>

我正在尝试让它向我的远程服务器发送命令。

【问题讨论】:

  • 由于您将这些登录信息定义为全局变量,因此您必须在函数内部使用 global 关键字 stackoverflow.com/questions/15687363/… 定义要使用的全局变量
  • 最好将这些登录信息作为参数传递给函数,而不是使用全局变量

标签: php ssh2-exec


【解决方案1】:

试试这些改变:

function execute($address,$user, $password, $command){
    $connection = ssh2_connect($address, 22);
    if(ssh2_auth_password($connection, $user, $password)){
        echo ssh2_exec($connection, $command);
    }else {
        die("Could not connect to server...");
    }
}

execute($address,$user, $password, $command);

您在函数内部引用的变量实际上并不可用,它们需要在调用函数时作为参数传入,就像我在上面的 sn-p 中所做的那样,或者通过在函数内部全局声明它们.

【讨论】:

  • 为什么 OP 应该“尝试这些更改”? 好的答案将始终解释所做的事情以及为什么以这种方式完成,不仅是为了 OP,也是为了 SO 的未来访问者。跨度>
  • 谢谢,我已经更新了答案,以后会牢记这一点。干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2013-03-06
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
相关资源
最近更新 更多