Attempting to connect to a remote Solaris server from PHP site
I want to connect to the Solaris server from Windows OS with the PHP site, to execute some shell script on the Solari开发者_高级运维s server. The site just hang there and did nothing.
<?php
exec('ssh root@192.168.175.128');
echo exec('cd Desktop');
echo exec('./chong.sh');
?>
I'm guessing that the problem here is that you are connecting to the Solaris Box via ssh and not doing anything with the process.
When you call ssh root@192.168.175.128
you start an ssh session with the Solaris box. This process will then hang around waiting for you to tell it what to do:
- It may be asking you for a password if you don't have a certificate set up.
- Even if it isn't, it will hang at the prompt on the remote box waiting for a command, like any normal terminal would.
Even then, you are attempting to execute the other commands on the local machine, with the subsequent calls to exec()
. In order to execute anything on the remote machine, you will need to pass the commands into the ssh process you created.
Try proc_open() instead:
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "errors.txt", "a") // stderr is a file to write to
);
$process = proc_open('ssh root@192.168.175.128', $descriptorspec, $pipes);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to errors.txt
// Clear the input buffer before we send anything - you may need to parse
// this to determine when to send the data
while (!fgets($pipes[1])) continue;
// You may need to send a password
// fwrite($pipes[0],"password\n");
// while (!fgets($pipes[1])) continue;
// Send the first command and wait for a prompt
fwrite($pipes[0],"cd Desktop\n");
while (!fgets($pipes[1])) continue;
// Send the next command
fwrite($pipes[0],"./chong.sh\n");
// Close the STDIN stream
fclose($pipes[0]);
// Fetch the result, output it and close the STDOUT stream
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
// Kill the ssh process and output the return value
$return_value = proc_close($process);
echo "\ncommand returned $return_value\n";
}
EDIT Thinking about it, if this is a local machine and you don't need to worry about security, you may find it easier to connect via telnet rather than ssh, because if you do this you can simply use fsockopen() instead of messing around with multiple IO streams, as you need to do with proc_open().
精彩评论