-2

我想运行一个包含 IP 数组的 PHP,并从每个 IP 中删除一个特定文件。

像这样的东西:

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

在 delete.sh 文件中我会有这样的东西

ssh user@$1 'rm /my/dir/filespath/$2 '

所有服务器都有相同的路径和文件,还有用户名和密码有什么建议吗?

编辑:

执行 sh 文件的 PHP 文件位于安全管理员页面中,IP 是本地 IP (192.168.1.25, 26, 27)

如果我想从路径中删除所有文件,我会做这样的事情(就像我现在正在做的那样)

ssh user@192.168.1.25 '/usr/bin/find /my/dir/filespath/* -type d -exec /bin/rm -fr {} \;'
ssh user@192.168.1.26 '/usr/bin/find /my/dir/filespath/* -type d -exec /bin/rm -fr {} \;'
ssh user@192.168.1.27 '/usr/bin/find /my/dir/filespath/* -type d -exec /bin/rm -fr {} \;'

但我只想删除一个特定文件,例如:/my/dir/filespath/other/folder/file.txt

由于我将添加更多服务器或更改它们的 IP,我需要它们是可变的 [这现在不是强制性的]

4

2 回答 2

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 user@'.$ip.' '.$command);
        sleep(1);// sleep 1 sec for letting the command time to delete the file (could be less)
    }
}
exit();

完美运行!当然,delete.php 文件的安全性更高,这只是一个示例版本

谢谢大家!

于 2013-02-08T21:33:18.310 回答
0

在您的远程服务器上,您可以托管一个文件,我们称之为 callme.php

callme.php 会像

<?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;
    }
   ?>

这可能不是最好的方法,但它可以工作......我刚刚快速写出的上述代码,所以一些代码可能需要精打细算,您需要确保所有文件都具有适当的权限。

于 2013-02-06T22:08:45.600 回答