[英]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连接和调用远程脚本的两个主题:
And two ways to use it in php:以及在 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.