【问题标题】:Executing shell commands via PHP?通过 PHP 执行 shell 命令?
【发布时间】:2019-11-19 14:13:44
【问题描述】:

我正在尝试 ssh 到远程服务器以检查特定文件是否存在。

我可以在命令行中进行 ssh,但每当我尝试使用我的脚本时,它不会返回任何内容/我必须输入“exit”并按 Enter 键才能返回命令行。

步骤:

  1. ssh root@website.com
  2. cd ..
  3. ls ATMEXTRACT

我将所有这些命令放入输出中,因此它们看起来像这样:

$output = shell_exec("ssh root@website.com");
$ouput1 = shell_exec("cd ..");
$ouput2 = shell_exec("ls *ATMEXTRACT*");

echo($output2);

我很困惑为什么这直接在命令行中工作但在脚本中失败。非常感谢任何帮助

【问题讨论】:

  • 这个问题最好用很长的解释来回答 shell_exec 真正的工作原理,并在这里解释你的误解。我不知道从哪里开始,但与此同时,对于您正在做的事情,请考虑 PHP 的 SSH2 extension
  • 还要考虑 PHP 的 FTP 函数,和this other question

标签: php linux shell ssh remote-server


【解决方案1】:

以下是您以交互方式执行的操作:

  • 在当前shell中运行ssh root@website.com
    • ssh 中输入cd ..
    • ssh 中输入ls *ATMEXTRACT*
    • ssh 中输入exit,现在退出
  • 回到原来的外壳中

这是您在脚本中执行的操作:

  • 在新的 shell 中运行 ssh root@website.com 并退出
  • 在第二个 shell 中运行 cd .. 并退出它
  • 在第三个 shell 中运行 ls *ATMEXTRACT* 并退出它

您可以尝试打开 ssh 命令并与之交互,但您也可以省去麻烦并使用ssh 的命令行功能来指定要运行的命令:

$output = shell_exec("ssh root@website.com 'cd .. && ls *ATMEXTRACT*'");

请注意,这可能会因 PHP 网站脚本而失败,因为您需要设置身份验证机制。即使ssh root@website.com 在您手动登录 Web 服务器并尝试时无需密码连接也是如此。

【讨论】:

  • 这似乎奏效了!太感谢了!我非常感谢您的帮助和详尽的解释:)
  • @TaraMashkory 当有人回答你的问题时,你应该标记为已接受
【解决方案2】:

我会推荐你​​使用 PHP 的 ssh2 模块。这将帮助您连接可通过适当的 SSH 端口访问的任何远程服务器。

您需要检查是否在您的主机服务器上安装了一些模块,例如 OpenSSL 和 ssh2。 如果不是,请检查此https://ehikioya.com/install-ssh2-php/ 并安装以上模块。

一旦安装并启用这些模块。

遵循此代码。

$server="website.com";  
$server_pwd="Password";

//creating connection using server credentials
$connection = ssh2_connect($server, 22);

//authenticating username and password
if(ssh2_auth_password($connection, 'root', $server_pwd)){
    echo "connected"
}else{

    echo "could not connect to server";
}

ssh2_exec($connection, "ls /FULL_PATH/ATMEXTRACT"); //run your command here 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 2011-08-15
    相关资源
    最近更新 更多