简体   繁体   中英

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. Script should be executed on remote machine from php level. I found the following topics:

Two topics about ssh connection and calling remote script:

  1. How to use SSH to run a shell script on a remote machine?
  2. https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password

And two ways to use it in php:

  1. Run Bash Command from PHP
  2. get result from ssh2_exec , http://php.net/manual/en/function.ssh2-exec.php

I tried to use the following code in my symfony2 application:

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). 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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