2013-02-06 37 views
-2

我想運行一個包含IP數組的PHP,並從每個IP刪除特定文件。PHP - 執行bash .sh文件以從不同服務器上刪除文件

事情是這樣的:

foreach($servers as $ip){   
    shell_exec("sh /my/dir/delete.sh ".$ip." ".$file); 
} 

,並在delete.sh文件我有這樣的事情

ssh [email protected]$1 'rm /my/dir/filespath/$2 ' 

所有服務器都具有相同的路徑和文件,還有用戶名和密碼 有什麼建議嗎?

編輯:

執行的SH文件的PHP文件是在一個安全管理員頁面,以及IP的本地IP地址(192.168.1.25,26,27)

我會做這樣的事情這一點,如果我想從路徑中刪除所有文件(如我現在這樣做)

ssh [email protected] '/usr/bin/find /my/dir/filespath/* -type d -exec /bin/rm -fr {} \;' 
ssh [email protected] '/usr/bin/find /my/dir/filespath/* -type d -exec /bin/rm -fr {} \;' 
ssh [email protected] '/usr/bin/find /my/dir/filespath/* -type d -exec /bin/rm -fr {} \;' 

但我想只刪除一個特定的文件,該文件可能是在例如:/我的/ DIR/filespath/other/folder/file.txt

而且我會添加更多的服務器或更改其IP的,我需要他們變量[這並不是強制性的,現在]

+1

現在的解決方案到底出了什麼問題? –

+1

也許應該是'/ bin/sh /my/dir/delete.sh ...'而不僅僅是呃 – fedorqui

+0

你確定沒有更好的方法來做到這一點嗎?安全方面,你不在一個好的地方。 – Oerd

回答

0

在您的遠程服務器上,你可以舉辦一個文件允許調用它callme.php

callme.php將soemthing像

<?php 
exec("/bin/sh /path/to/deletefiles.sh"); 
echo 'OK'; 
?> 

deletefiles.sh會像

#!/bin/sh 
rm -rf /path/to/file/to/delete.txt 
echo 'Ok' 

最後你的命令的服務器上,你可以有一個bash文件中像這樣:

#!/bin/sh 
servers+=("http://1.2.3.4") 
servers+=("http://1.2.3.5") 
servers+=("http://1.2.3.6") 
servers+=("http://www.yoursite.com") 
file='/callme.php' 

for i in "${servers[@]}" 
do 
: 
    echo $i$file 
    curl -s $i$file 
    sleep 5 
done 

,或者如果你寧願做遠程文件調用PHP中

<?php 

$servers[]="http://1.2.3.4"; 
$servers[]="http://1.2.3.5"; 
$servers[]="http://1.2.3.6"; 
$servers[]="http://www.yoursite.com"; 

$file = "/callme.php"; 

foreach ($servers as $k => $v){ 
     $url = $v.$file; 
     $results[] = curl_download($url); 
} 
var_dump($results); 

function curl_download($Url) { 
     if (!function_exists('curl_init')) { 
      die('Sorry cURL is not installed!'); 
     } 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $Url); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
     $output = curl_exec($ch); 
     curl_close($ch); 
     return $output; 
    } 
    ?> 

它可能不是做的最好的方式,但它的作品...上面的代碼我只是很快寫出來的,所以一些代碼可能需要很快,你需要確保你的所有文件都有適當的權限。

+0

我必須將路徑/文件傳遞給bash文件,這是在php文件中生成的。這就是我遇到麻煩的地方,感謝您的建議 – ralvarezh

+0

如果您將路徑作爲參數傳遞給php腳本? – 244an

+0

試過,如例子 – ralvarezh

0

** **解決

我做了這個請求,從管理員

if($file){ 
    $res = file_get_contents("http://[current server IP]/delete.php?token=12345&p=".$file); 
    echo $file; 
} 
echo $res; 

而且delete.php文件有這個

if($_GET['token']!='12345') exit(); 

$ips = array(192.168.1.25,192.168.1.26,192.168.1.27); 

$file = $_GET['p']; 
$file = str_replace(array('../','*','./'),'',$file); 
if($file != ""){ 
    $command = '"/bin/rm -f /my/dir/filespath/'.$file.'"'; 
    foreach($ips as $ip){ 
     echo shell_exec('ssh [email protected]'.$ip.' '.$command); 
     sleep(1);// sleep 1 sec for letting the command time to delete the file (could be less) 
    } 
} 
exit(); 

完美的作品! 當然在delete.php文件中有更多的安全性,它只是一個示例版本

謝謝大家!