简体   繁体   English

如何使用 php 在远程服务器上运行本地 bash 脚本

[英]How to run local bash script on remote server using php

I store bash script as a string in db and I need to call it on user demand.我将 bash 脚本作为字符串存储在 db 中,我需要根据用户需求调用它。 Script should be executed on remote machine from php level.脚本应该从 php 级别在远程机器上执行。 I found the following topics:我找到了以下主题:

Two topics about ssh connection and calling remote script:关于ssh连接和调用远程脚本的两个主题:

  1. How to use SSH to run a shell script on a remote machine? 如何使用 SSH 在远程机器上运行 shell 脚本?
  2. https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password

And two ways to use it in php:以及在 php 中使用它的两种方法:

  1. Run Bash Command from PHP 从 PHP 运行 Bash 命令
  2. get result from ssh2_exec , http://php.net/manual/en/function.ssh2-exec.php 从 ssh2_exec 获取结果http: //php.net/manual/en/function.ssh2-exec.php

I tried to use the following code in my symfony2 application:我尝试在我的 symfony2 应用程序中使用以下代码:

First attempt:第一次尝试:

$connection = ssh2_connect('IP_ADDRESS', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, "'bash -s' < ".$script);
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$output = stream_get_contents($stream_out);
//result => output = empty string

Second:第二:

$old_path = getcwd();
chdir('/path_to_script_directory');
$output = shell_exec("ssh user@server 'bash -s' < test");
chdir($old_path);

or

$old_path = getcwd();
chdir('/path_to_script_directory');
$output = shell_exec("ssh user@server 'bash -s' < ".$script);
chdir($old_path);
//result => output = null

As in examples above I tried two cases with "test" script and string script ($script variable).与上面的示例一样,我尝试了“test”脚本和字符串脚本($script 变量)两种情况。 Second option is preffered by me.我更喜欢第二种选择。 Both cases contains simple script:这两种情况都包含简单的脚本:

#!/bin/bash

ifconfig

Thank you in advance!提前谢谢你!

Here is a project that will give you a real bash shell on a remote server: https://github.com/merlinthemagic/MTS这是一个可以在远程服务器上为您提供真正的 bash shell 的项目: https : //github.com/merlinthemagic/MTS

Install and run the following commands:安装并运行以下命令:

//login to the remote server and get a shell:

$shellObj       = \MTS\Factories::getDevices()->getRemoteHost('ip_address')->setConnectionDetail('username', 'password')->getShell();

//rather than executing your script, just run the command:

$returnData = $shellObj->exeCmd("ifconfig");

echo $returnData; //string containing the interface config of the remote server.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM