Linux实战之inotify与ftp实现文件同步
inotify:实现文件目录的状态监控
ftp:实现文件传输
1.安装inotify
下载并上传工具包:inotify-tools-3.13.tar.gz
[root@localhost tools]# tar -zxvf inotify-tools-3.13 #解压,工具包所在的目录
[root@localhost inotify-tools-3.13]# ./configure --prefix=/usr/local/inotify #进入解压后的目录
[root@localhost inotify-tools-3.13]# make
[root@localhost inotify-tools-3.13]# make install #安装
[root@localhost inotify-tools-3.13]# vim /etc/sysctl.conf #修改参数,添加:fs.inotify.max_user_instances=130
2.安装ftp与lftp命令
[root@localhost tools]# yum -y install vsftpd #联网
[root@localhost tools]# yum -y install vsftpd
[root@localhost tools]# vim /etc/vsftpd/vsftpd.conf #修改配置文档,关闭匿名访问:anonymous_enable=NO
[root@localhost tools]# systemctl status vsftpd #查看ftp服务状态
[root@localhost tools]# systemctl stop vsftpd #停止ftp服务
[root@localhost tools]# systemctl start vsftpd #启动ftp服务
[root@localhost tools]# systemctl restart vsftpd #重启ftp服务
[root@localhost tools]# yum -y install lftp #联网安装lftp命令
[root@localhost tools]# setenforce 0 # FTP用户登录创建文件夹失败 不重启系统
[root@localhost tools]# vi /etc/selinux/config 修改为SELINUX=disabled #FTP用户登录创建文件夹失败重启系统
3.编写同步脚本
3.1监控监本
[root@localhost myshell]# vim inotify_start.sh
#!/bin/bash
#chkconfig:345 88 14
#/tool/share 本地监控的目录
# -mrq: 始终保持监听状态;递归查询目录;打印出监控事件
# -e :定义监控的事件,modify, create, move, delete
/usr/local/inotify/bin/inotifywait -mrq -e 'create,delete,close_write,attrib,moved_to' --timefmt '%Y-%m-%d %H:%M' --format '%T %w%f %e' /tools/share | while read LINE
do
if [[ $LINE = *CREATE* ]];then
/myshell/lftp_toftp.sh
elif [[ $LINE = *MOVE* ]];then
/myshell/lftp_toftp.sh
fi
done
inotifywait常用参数:
--timefmt 时间格式
%y年 %m月 %d日 %H小时 %M分钟
--format 输出格式
%T时间 %w路径 %f文件名 %e状态
-m 始终保持监听状态,默认触发事件即退出。
-r 递归查询目录
-q 打印出监控事件
-e 定义监控的事件,可用参数:
open 打开文件
access 访问文件
modify 修改文件
delete 删除文件
create 新建文件
3.2同步脚本
[root@localhost myshell]# vim lftp_toftp.sh
#!/bin/bash
lftp -c "set ftp:list-options -a;
open ftp://eafftp:eafftp@192.168.249.132;
lcd /tools/share/; #本地监控的目录
cd /home/eafftp; #远程同步的目录
mirror --reverse --use-cache --verbose --allow-chown --allow-suid --no-umask --parallel=2 --include-glob * "
3.3开机启动
[root@localhost myshell]# cp inotify_start.sh /etc/rc.d/init.d/ #复制监控脚本至服务器启动时访问的目录
[root@localhost myshell]# cd /etc/rc.d/init.d
[root@localhost myshell]# chkconfig --add inotify_start.sh
[root@localhost myshell]# chkconfig inotify_start.sh