2013-02-06 38 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文件中有更多的安全性,它只是一个示例版本

谢谢大家!