使用php结合rsync、inotify实现的实时备份脚本!

WBOY
Release: 2016-06-23 13:20:04
Original
1089 people have browsed it

1. php脚本<?php         #解析配置文件     $arr=parse_ini_file('config.ini',true);     #获取符合“监控”要求的目录格式的路径          $dirListen=implode(' ',$arr['srcdir']);     # 获取符合“同步目录”要求的格式的目录路径     $sdDir=dir_path_parse($arr['srcdir'],$arr['dstdir']);     #运行程序后先同步一次     rsync_data($sdDir['src'],$sdDir['dst']);     #监控文件系统变化     $p=popen('inotifywait -mrq --format "%T %w\%f %e" -e create,modify,delete,move '.$dirListen,'r');     #文件系统发生变化时,进行数据同步     while($f=fgets($p)){            #重构字符串用以日志显示        $arr=explode(' ',trim($f));                $event['file']=implode(array_splice($arr,2,-1));        list($event['date'],$event['time'],$event['oper'])=$arr;                #print_r($event);        $strLog='来自'.gethostbyname(gethostname()).'的操作:'.$event['oper'].'  '.$event['file'].' 于 '.$event['date'].'_'.$event['time'].' 同步备份到服务器上...';        $strLog .= rsync_data($sdDir['src'],$sdDir['dst'])."\r\n";        file_put_contents('databak.log',$strLog,FILE_APPEND);        echo $strLog;            }     #释放资源     pclose($p);########################################函数################################################         #同步备份    function rsync_data($srcdir,$dstdir){            exec("rsync -togrvzp --delete --progress $srcdir $dstdir");            return "OK";    }            #源目录和目的目录路径处理    function dir_path_parse($srcdir,$dstdir){        if(php_uname('s') == 'Windows NT'){            foreach ($srcdir as $k=>$v) {                $srcdir[$k]='/cygdrive/'.preg_replace('/[^\w-\.]{1,}/','/',$v);            }            $srcdirAll=implode(' ', $srcdir);            $dstdir=implode('::',$dstdir);            return array('src'=>$srcdirAll, 'dst'=>$dstdir);        }else{            $srcdirAll=implode(' ', $srcdir);            $dstdir=implode('::',$dstdir);            return array('src'=>$srcdirAll, 'dst'=>$dstdir);        }    }
Copy after login

2、config.ini #用来配置需要备份的目录

[srcdir]dir1=d:\test ;目录不能以"\"结尾dir2=d:\scan[dstdir]host=10.74.60.71 ;rsync服务器地址shareDirName=zhangsan ;rsync服务器共享出来的目录
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!