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:
- How to use SSH to run a shell script on a remote machine?
- https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password
And two ways to use it in php:
- Run Bash Command from PHP
- 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!