我试图从远程服务器执行一个php文件,就像我在远程服务器控制台输入 "php example.php "一样。目前它一直试图返回到原始服务器。我试过直接从php执行,Net_SSH2,以及执行一个.sh。我不知道我哪里出错了。我会尽力分析这个问题。
数据库
------------------------
| ID | password |
------------------------
| 50 | testpassword |
------------------------
文件
主服务器(10.0.0.10):carrytoserver.php, execpw.php, execpw2.php, execpw3.php, execute.php。
App Server (10.0.0.20): grabid.php, login.php, makeconfig.php, local_script.php, carry.txt。
所有权限为777
主站
执行.php
<?php
$password="testingpassword";
include('carrytoserver.php');
include('execpw.php');
?>
carrytoserver.php
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('10.0.0.20');
if (!$ssh->login('root', 'serverpassword')) {
exit('Login Failed');
}
echo $ssh->exec("echo $password > /test/example/carry.txt");
?>
execpw.php
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('10.0.0.20');
if (!$ssh->login('root', 'serverpassword')) {
exit('Login Failed');
}
echo $ssh->exec('php /test/example/grabid.php');
?>
APPSERVER
携带.txt
testpassword
grabid.php
<?php
include 'login.php';
$carrypw=file_get_contents('carry.txt');
$password=str_replace("\n","", $carrypw);
$con=mysql_connect("$host", "$username", "$dbpassword")or die("cannot connect");
mysql_select_db("$db_name") or die ("cannot select DB");
$result = mysql_query("SELECT * FROM example
WHERE password='$password'");
while($row = mysql_fetch_array($result)) {
$id = $row['ID'];
}
include 'makeconfig.php';
?>
makeconfig.php
<?php
$return_arr = array('ID' => $id, 'password' => "$password");
$json_data = json_encode($return_arr);
file_put_contents("config.json", $json_data);
?>
本地脚本
#! /bin/bash
echo "php grabid.php"
execute.php将执行carrytoserver.php,它将携带密码到10.0.0.20并将其放入carry.txt中。然后执行execpw.php,在10.0.0.20上执行grabid.php。grabid.php会抓取与密码相关的ID。
一旦它做完这些,10.0.0.20应该有$password和$id。Grabid.php将执行makeconfig.php并为应用程序创建json配置文件。
目前它将把密码带到10.0.0.20,并执行grabid.php,但不会创建json文件或继续运行。如果我在grabid.php的顶部添加$password,然后从10.0.0.20控制台运行,它就会运行。
如果我把echo "hi";加到grabid.php的末尾,然后从头开始运行,它就会在10.0.0.10服务器控制台中回荡 "hi"。
我还在execpw.php文件中尝试了一些其他的东西。
execpw2.php
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('10.0.0.20');
if (!$ssh->login('root', 'serverpassword')) {
exit('Login Failed');
}
echo $ssh->exec('/test/example/local_script.sh');
?>
execpw3.php
<?php
$executephp="ssh [email protected] 'php grabid.php'";
exec ($executephp);
?>
所有的结果都是一样的。我很抱歉信息量过大,但我尽量提供更多的信息,我想在远程服务器上执行一个php文件,就像在远程服务器的控制台输入 "php example.php "一样。
EDIT :
如果carry.txt和grabid.php的路径是正确的,那么你应该把grabid.php的行数改为如下。
$carrypw=file_get_contents('/test/example/carry.txt');
我把 "file_put_contents "改成绝对路径就可以解决了
<?php
$return_arr = array('ID' => $id, 'password' => "$password");
$json_data = json_encode($return_arr);
file_put_contents("/test/example/config.json", $json_data);
?>