我有一个PHP脚本,使用
在我的Windows机器上运行.bat文件$ result = system(“cmd / C nameOfBatchFile.bat”);
这设置了一些环境变量,用于从命令行调用Amazon EC2 API。
如何从Linux服务器执行相同的操作?我已将我的.bat文件重命名为shell(.sh),并在设置env vars时将脚本更改为使用'export'。我已经通过运行putty终端的代码进行了测试,并且它做了应有的事情。所以我知道脚本中的命令很好。我如何从PHP运行它?我尝试使用新的文件名运行与上面相同的命令,我没有收到任何错误,或者找不到文件等,但它似乎不起作用。
我从哪里开始尝试解决这个问题?
---------------------------------- UPDATE ------------ -------------------
以下是调用shell文件的PHP脚本 -
function startAmazonInstance() {
$IPaddress = "1.2.3.4"
$resultBatTemp = system("/cmd /C ec2/ec2_commands.sh");
$resultBat = (string)$resultBatTemp;
$instanceId = substr($resultBat, 9, 10);
$thefile = "ec2/allocate_address_template.txt";
// Open the text file with the text to make the new shell file file
$openedfileTemp = fopen($thefile, "r");
contents = fread($openedfileTemp, filesize($thefile));
$towrite = $contents . "ec2-associate-address -i " . $instanceId . " " . $IPaddress;
$thefileSave = "ec2/allocate_address.sh";
$openedfile = fopen($thefileSave, "w");
fwrite($openedfile, $towrite);
fclose($openedfile);
fclose($openedfileTemp);
system("cmd /C ec2/mediaplug_allocate_address_bytemark.sh");
}
这是.sh文件 - ec2_commands.sh
#!/bin/bash
export EC2_PRIVATE_KEY=$HOME/.ec2/privateKey.pem
export EC2_CERT=$HOME/.ec2/Certificate.pem
export EC2_HOME=$HOME/.ec2/ec2-api-tools-1.3-51254
export PATH=$PATH:$EC2_HOME/bin
export JAVA_HOME=$HOME/libs/java/jre1.6.0_20
ec2-run-instances -K $HOME/.ec2/privateKey.pem -C $HOME/.ec2/Certificate.pem ami-###### -f $HOME/.ec2/aws.properties
我已经能够从命令行运行此文件,所以我知道命令可以正常工作。当我在Windows上工作时,实例启动会有延迟,我可以将结果回显到屏幕上。现在没有任何延迟,好像什么也没发生。
答案 0 :(得分:4)
在shell脚本的第一行添加hash-bang。
#!/bin/bash
然后给它执行可执行标志。
$ chmod a+x yourshellscript
然后,您可以使用系统从PHP调用它。
$result = system("yourshellscript");
答案 1 :(得分:2)
$result = system("/bin/sh /path/to/shellfile.sh");
答案 2 :(得分:1)
脚本可执行吗?如果没有,请这样做:
$ chmod a+x script.sh # shell
system ("/path/to/script.sh"); // PHP
或通过翻译启动它:
system("sh /path/to/script.sh"); // PHP
是否在shell脚本中指定了解释器(即。#!/bin/sh
行)?
答案 3 :(得分:0)
你试过shell_exec()吗?