2010-05-11 47 views
2

我有一個運行使用什麼是Linux相當於使用system()

$結果我的Windows機器上的一個.bat文件PHP腳本從PHP在Windows上運行的.bat文件的=系統(「CMD/C nameOfBatchFile.bat「);

這設置了一些環境變量,用於從命令行調用Amazon EC2 API。

如何從Linux服務器執行同樣的操作?我已將我的.bat文件重命名爲shell(.sh),並在設置env變量時將腳本更改爲使用'export'。我已經通過從膩子終端運行代碼進行了測試,並且它做了它應該做的事情。所以我知道腳本中的命令很好。我如何從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

你試過shell_exec()嗎?

2
$result = system("/bin/sh /path/to/shellfile.sh"); 
+0

我不知道你需要執行許可,如果你直接把它給殼? – paxdiablo 2010-05-11 14:59:06

+0

好吧,我試過這個,但它似乎仍然沒有運行該文件。是相對於PHP腳本文件的路徑嗎?我檢查了這些文件的權限,他們是777 – undefined 2010-05-11 15:01:18

+0

腳本不需要執行權限,因爲您沒有執行它 - 您正在執行'/ bin/sh'並將腳本傳遞給其運行。 – meagar 2010-05-11 15:10:17

4

在你的shell腳本的第一行放置一個hash-bang。

#!/bin/bash 

然後給它一個可執行標誌。

$ chmod a+x yourshellscript 

然後,您可以使用系統從PHP調用它。

$result = system("yourshellscript"); 
1

腳本是否可執行文件?如果不是這樣,做起來很:

$ chmod a+x script.sh   # shell 

system ("/path/to/script.sh"); // PHP 

或通過翻譯啓動它:

system("sh /path/to/script.sh");  // PHP 

在shell腳本解釋器指定(即#!/bin/sh線。)?

相關問題