如何在Linux中局域网实时监控软件目录的变化

工作中我们可能会遇到一些问题,比如系统部署过程中配置文件在多个主机之间的同步问题,或是和其他系统对接的时候,需要以其他系统输出的文件作为输入的时候,这时需要我们实时的监控文件目录的变化,用以做出响应。通常我们可能的选择是实时的监测目录信息,不断去获取目录信息来判断文件目录是否有变化。但在linux系统下,系统内核提供了一个机制Inotify,用以通知文件目录的变化。
Inotify 是一个 Linux特性,它监控文件系统操作,比如读取、写入和创建。Inotify 反应灵敏,用法非常简单,并且比 cron 任务的繁忙轮询高效得多。详细说明大家可以查询相关资料。
使用Inotify的基本步骤
一、初始化,并指定监控目录
int fd=inotify_init();//初始化
int wd=inotify_add_watch(fd,path.c_str(),IN_MODIFY|IN_CREATE|IN_DELETE);//添加监视
下面分享我在工作实现的一个简单监控目录小程序:
程序主要包括三个文件:filemonitor.h,filemonitor.cpp和main.cpp
1 #ifndef FILEMONITOR_H
2 #define FILEMONITOR_H
3 #include&iostream&
4 #include&map&
5 #include&vector&
6 using namespace
7 enum EventType{
13 typedef struct{
string//路径
EventT//事件类型
int fileT//0表示文件夹,1表示文件
18 typedef struct{
string//文件路径
int//过期时间
21 } FileI
22 class FileMonitor
24 private:
string//监控根目录
map&int,string& monitorM//监控列表
long//文件过期时间
vector&FileInfo *& fileL
void monitorSubFolder(string path);
void (*listener)(const Event
void deleteFile();
33 public:
FileMonitor(string path,void (*listener)(const Event
*),int expire=180);
~FileMonitor();
int start();
39 #endif // FILEMONITOR_H
1 #include "filemonitor.h"
2 #include&string.h&
3 #include&iostream&
4 #include &stdio.h&
5 #include &dirent.h&
6 #include&stdlib.h&
7 #include&sys/types.h&
8 #include&sys/inotify.h&
9 #include&time.h&
10 using namespace
11 #define EVENT_SIZE
( sizeof (struct inotify_event) )
12 #define BUF_LEN
( 1024 * ( EVENT_SIZE + 16 ) )
13 FileMonitor::FileMonitor(string path,void (*listener)(const Event
*),int expire)
this-&listener=
this-&expire=60;//expire*24*60*60;
fd=inotify_init();
cout&&"innotify_init failed"&&
monitorSubFolder(path);
24 int FileMonitor::start()
char buffer[BUF_LEN];
bool start=true;
while(start)
int length=0,i=0;
length=read(fd,buffer,BUF_LEN);
if(length&0)
cout&&"read none"&&
while ( i & length )
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
if ( event-&len &&event-&name[0]!='.'&&event-&name[strlen(event-&name)-1]!='~') //同时过滤隐藏文件和临时文件
if ( event-&mask & IN_CREATE )
Event *args=new E
if ( event-&mask & IN_ISDIR )
string path=monitorMap[event-&wd]+"/"+event-&
args-&path=
args-&fileType=0;
args-&type=CREATE;
monitorSubFolder(path);
string path=monitorMap[event-&wd]+"/"+event-&
args-&path=
args-&fileType=1;
args-&type=CREATE;
now=time(NULL);
FileInfo * fileInfo=new FileInfo();//将文件信息添加到监控列表中
fileInfo-&path=
fileInfo-&expire=now+//设置过期时间
if(strcmp(event-&name,"stop")==0)//如果新建文件名为stop则退出程序
fileInfo-&expire=//设置过期时间
start=false;
fileList.push_back(fileInfo);
if(listener!=NULL)
listener(args);
else if ( event-&mask & IN_DELETE )
Event *args=new E
if ( event-&mask & IN_ISDIR )
string path=monitorMap[event-&wd]+"/"+event-&
args-&path=
args-&fileType=0;
args-&type=DELETE;
inotify_rm_watch(fd,event-&wd);//移除监视
monitorMap.erase(event-&wd);//
string path=monitorMap[event-&wd]+"/"+event-&
args-&path=
args-&fileType=1;
args-&type=DELETE;
if(listener!=NULL)
listener(args);
else if ( event-&mask & IN_MODIFY )
Event *args=new E
if ( event-&mask & IN_ISDIR )
string path=monitorMap[event-&wd]+"/"+event-&
args-&path=
args-&fileType=0;
args-&type=MODIFY;
string path=monitorMap[event-&wd]+"/"+event-&
args-&path=
args-&fileType=1;
args-&type=MODIFY;
if(listener!=NULL)
listener(args);
i += EVENT_SIZE + event-&
deleteFile();
128 //监控子目录
129 void FileMonitor::monitorSubFolder(string path)
int wd=inotify_add_watch(fd,path.c_str(),IN_MODIFY|IN_CREATE|IN_DELETE);
monitorMap[wd]=//添加到监视列表
struct dirent* ent = NULL;
pDir=opendir(path.c_str());
if(pDir==NULL)
cout&&"invalid path"&&
while (NULL != (ent=readdir(pDir)))
if(ent-&d_type==4){
if(ent-&d_name[0]!='.')
string subPath=path+"/"+ent-&d_
monitorSubFolder(subPath);
if(listener!=NULL)
int len=strlen(ent-&d_name);
if(ent-&d_name[0]!='.'&&ent-&d_name[len-1]!='~')
string filename=path+"/"+ent-&d_
Event *args=new E
args-&path=
args-&fileType=1;
args-&type=CREATE;
now=time(NULL);
FileInfo * fileInfo=new FileInfo();//将文件信息添加到监控列表中
fileInfo-&path=
fileInfo-&expire=now+//设置过期时间
fileList.push_back(fileInfo);
listener(args);
174 void FileMonitor::deleteFile()
now=time(NULL);
for(vector&FileInfo *&::iterator it=fileList.begin();it!=fileList.end();)
if((*it)-&expire&=now)
if(!remove((*it)-&path.c_str()))
cout&&(*it)-&path&&" expired has been deleted"&&
it=fileList.erase(it);
cout&&"delete "&&(*it)-&path&&" failure"&&
196 FileMonitor::~FileMonitor()
for (map&int, string&::iterator i=monitorMap.begin(); i!=monitorMap.end(); i++)
inotify_rm_watch(fd,i-&first);//移除监视
monitorMap.clear();
close(fd);
如果大家不想自己写代码实现文件监控,现在也有一个工具能够帮助我们监控文件目录变化,这就是inotify-tools,这个工具配合rsync可以实现文件实时同步的功能。
下面给大家介绍一下这个工具的使用方法
测试主机地址:A、192.168.20.9
B、192.168.20.20测试目的将A主机目录/home/dmx/sync/test/的内容同步到B主机 /home/d5000/dmx/test目录下任意修改A主机同步目录下的内容,对应B主机的目录也会自动修改。
需要安装的软件有inotify-tools-3.14.tar.gzrsync-3.0.9.tar.gz软件装的基本步骤1、解压 进到解压后的目录2、执行./configure3、执行make4、执行make install服务端配置服务端需要安装rsync和inotify1、创建密码文件 echo "d5000"&rsync.passwd 其中"d5000"表示登录B主机的密码,这里用户名不需要指定,稍后将会在脚本中设置2、创建执行脚本测试脚本位于startSync.sh#!/bin/bashSRC='/home/dmx/sync/test/'DES='d.20.20::web'/usr/local/bin/inotifywait -mr --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' -e modify,delete,create,attrib ${SRC} |while read DATE TIME DIR FILEdo
FILECHAGE=${DIR}${FILE}
/home/dmx/rsync-3.0.9/rsync -av --progress --delete
--password-file=/home/dmx/rsync-3.0.9/rsync.passwd $SRC $DES #执行同步命令 echo "At ${TIME} on ${DATE}, file $FILECHAGE was backed up via rsync" && /home/dmx/sync/rsyncd.logdone脚本说明: SRC表示A主机同步的目录,DES表示B主机的地址,其中web表示一个模块,名称可以自定义 --password-file=/home/dmx/rsync-3.0.9/rsync.passwd指定密码文件的位置。其中,密码文件只能被当前运行脚本的用户访问,对应的命令是:chmod 600 rsync.passwd /home/dmx/sync/rsyncd.log指定日志文件的存放位置如果需要同步到多台主机,需要指定不同的DES,同时执行多条同步命令脚本示例:#!/bin/bashSRC='/home/dmx/sync/test/'DES1='d.20.20::web1'DES2='d.20.21::web2'/usr/local/bin/inotifywait -mr --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' -e modify,delete,create,attrib ${SRC} |while read DATE TIME DIR FILEdo
FILECHAGE=${DIR}${FILE}
/home/dmx/rsync-3.0.9/rsync -av --progress --delete
--password-file=/home/dmx/rsync-3.0.9/rsync.passwd $SRC $DES1 #执行同步命令
/home/dmx/rsync-3.0.9/rsync -av --progress --delete
--password-file=/home/dmx/rsync-3.0.9/rsync.passwd $SRC $DES2 #执行同步命令 echo "At ${TIME} on ${DATE}, file $FILECHAGE was backed up via rsync" && /home/dmx/sync/rsyncd.logdone客户端配置客户端只需要安装rsync1、创建密码文件 echo "d"&rsync.passwd 格式为"用户名:密码"2、创建rsync.conf配置文件客户端配置文件内容uid = nobodygid = nobodyuse chroot = nomax connections = 10strict modes = yespid file = /var/run/rsyncd.pidlock file = /var/run/rsync.locklog file = /var/log/rsyncd.log[web]#web表示模块,这里和A主机指定的模块相同path = /home/d5000/dmx/test #表示本地同步的目录comment = web fileignore errorsread only = nowrite only = nohosts allow =192.168.20.9 #允许连接的主机地址hosts deny = *list = falseuid = rootgid = rootauth users = d5000 #登录用户secrets file = /home/d5000/dmx/rsync-3.0.9/rsync.passwd #密码文件位置密码文件必须只能被运行rsync的用户访问,创建时以运行用户创建,然后执行chmod 600 rsync.passwd运行./rsync --daemon --config=/home/d5000/dmx/rsync-3.0.9/rsync.conf
这样就配置完成了。
阅读(...) 评论()如何实时侦测目录中文件变化?
[问题点数:50分,结帖人jwchc]
如何实时侦测目录中文件变化?
[问题点数:50分,结帖人jwchc]
不显示删除回复
显示所有回复
显示星级回复
显示得分回复
只显示楼主
2000年3月 总版技术专家分月排行榜第一
2000年4月 总版技术专家分月排行榜第三
2000年3月 Delphi大版内专家分月排行榜第三
匿名用户不能发表回复!|博客分类:
最近,有个项目需要及时删除Nginx服务生成的缓存文件,由于不是很了解Nginx缓存生成的策略,在网上也没有仔细找,经过大家讨论,最终希望引入liunx的inotify功能,监控某个liunx目录下的各种事件(create,delete,access等等).
想了解inotify的朋友,请参考以下两篇博文:
1.使用 inotify 监控 Linux 文件系统事件
2.inotify -- Linux 2.6 内核中的文件系统变化通知机制
如果看完两篇博文,你的想法是用C语言马上写一个监控文件的程序(我当初也这么想的),先别忙,看看下面的文章,马上向您介绍一下inotify-tools这个工具包,目前最新版是3.3版本,这个工具包几乎包含了目录和文件的监控点,也就是说,不用动手写C代码,已经有前人帮我写好了,我们可以直接通过bash脚本的调用完成这个功能.
1、先查看linux的内核是否支持inotify,支持inotify的内核最小为2.6.13,输入命令:uname –a。如下图所示,内核为2.6.27,应该支持inotify.如果不支持,我建议你选择一个高级别的linux内核.否则应该会有很多麻烦.
2、还可以通过如下命令查看系统是否支持inotify:ll /proc/sys/fs/inotify
如果有如下输出,表示系统内核已经支持inotify:
total 0
-rw-r--r-- 1 root root 0 Feb 21 01:15 max_queued_events
-rw-r--r-- 1 root root 0 Feb 21 01:15 max_user_instances
-rw-r--r-- 1 root root 0 Feb 21 01:15 max_user_watches
3.inotify-tools的下载和安装
下载地址:[url]http://downloads.sourceforge.net/inotify-tools/inotify-tools-3.13.tar.gz?modtime=&big_mirror=0
[/url]
安装过程:略.
4.内部命令介绍
系统下执行命令:man inotify、 man inotifywait、 man inotifywatch即可得到相应的帮助信息,表示inotify安装成功。
man inotify:
& 捕获文件系统的各种状态事件
&
inotify events
Description
File was accessed (read) (*)
Metadata changed (permissions, timestamps,
extended attributes, etc.) (*)
IN_CLOSE_WRITE
File opened for writing was closed (*)
IN_CLOSE_NOWRITE
File not opened for writing was closed (*)
File/directory created in watched directory (*)
File/directory deleted from watched directory (*)
IN_DELETE_SELF
Watched file/directory was itself deleted
File was modified (*)
IN_MOVE_SELF
Watched file/directory was itself moved
IN_MOVED_FROM
File moved out of watched directory (*)
IN_MOVED_TO
File moved into watched directory (*)
File was opened (*)
man inotifywait:
& 等待并监控某个目录或文件的状态改变,能够适时的通过liunx脚本等待并监控文件改变的事件,可以在事件发生时退出脚本,也可以在事件发生时输出一些信息.
--fromfile &file&& 只监控目录下文件状态的变化
-m, --monitor&&&&& 当事件发生后直接执行退出,-m 参数将不退出当前的shell脚本.
-r, --recursive&&& 递归监控当前目录下的所有文件和目录.(默认的文件和目录数最大是 8192个;如果不满足可以修改/proc/sys/fs/inotify/max_user_watches
--exclude &pattern&& 通过正则匹配文件名,大小写敏感.
--excludei &pattern&& 通过正则匹配文件名,大小写不敏感.
-t &seconds&&&&&&& 事件发生时的秒数.
& -e &event&&&&&&&& 监听那些事件的发生
--timefmt option&& 指定输出的时间格式
--format &fmt& &&& 输出指定时间格式.
&&&& %w
监控事件发生时的文件名或文件路径
&&&& %f
监控目录内部事件发生时文件名称
&&&& %e
监控指定的事件发生
&&&& %T
输出事件发生时的时间,--timefmt option指定格式
inotifywatch:
& 使用linux的inotify特性监控某段时间内的文件状态,并输出摘要报表.
样例:输出beagle目录下60秒内的访问和修改事件触发报表
% inotifywatch -v -e access -e modify -t 60 -r ~/.beagle
Establishing watches...
Setting up watch(es) on /home/rohan/.beagle
OK, /home/rohan/.beagle is now being watched.
Total of 302 watches.
Finished establishing watches, now collecting statistics.
Will listen for events for 60 seconds.
/home/rohan/.beagle/Indexes/FileSystemIndex/PrimaryIndex/
/home/rohan/.beagle/Indexes/FileSystemIndex/SecondaryIndex/
/home/rohan/.beagle/Indexes/KMailIndex/PrimaryIndex/
/home/rohan/.beagle/TextCache/
/home/rohan/.beagle/Log/
/home/rohan/.beagle/Indexes/FileSystemIndex/Locks/
/home/rohan/.beagle/Indexes/FileSystemIndex/
/home/rohan/.beagle/Indexes/KMailIndex/Locks/
/home/rohan/.beagle/TextCache/54/
/home/rohan/.beagle/TextCache/bc/
/home/rohan/.beagle/TextCache/20/
/home/rohan/.beagle/TextCache/62/
/home/rohan/.beagle/Indexes/KMailIndex/SecondaryIndex/
编写自己的监控脚本:
需求:由于使用Nginx的反向代理,生成本地缓存的策略,所以需要监控某个目录的新增或删除的变化,并将变化的文件名称输出到一个LOG中,带后续文件有修改时,可以通过该log定位文件地址,并删除该文件,及时向前端反映文件变更后的变化.
脚本; inodify_cache_list.sh
# A slightly complex but actually useful example
logfile="/opt/data/cache_list.txt"
temp_logfile="/opt/data/cache_tempfile.txt"
/usr/local/bin/inotifywait -mrq
--format '%w%f' -e moved_to /opt/data/proxy_cache_dir/|
echo "/usr/bin/printf \"delete "`grep -a 'KEY:' ${file}| sed -e s/KEY://g;`"\\r\\n\" | nc 127.0.0.1 11211,rm -f "${file} |tee -a $logfile | tee -a $temp_logfile
论坛回复 /
(0 / 7310)
浏览: 132561 次
来自: 北京
我用nodetool tpstats
发现有很多 flush ...
192.168.5.6
datacenter1 rac ...
Space used (total): Spa ...
lxiaodao 写道我在试验并发写入的时候(java客户端) ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'Linux系统实时监控_图文_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
Linux系统实时监控
&&Linux系统实时监控的瑞士军刀-Glances的用法
阅读已结束,下载本文需要
想免费下载本文?
定制HR最喜欢的简历
下载文档到电脑,同时保存到云知识,更方便管理
加入VIP
还剩3页未读,
定制HR最喜欢的简历
你可能喜欢博客分类:
在线演示:
Finder是一个web方式的文件管理器。Finder最主要的功能是超大日志文件的实时查看。
(程序员专用) 支持集群部署,允许你同时管理多台机器上的文件或者查看不同机器上的日志;
(程序员专用) grep支持,类似linux系统的grep命令,支持任意大小的文件,支持随时查看文件的任意位置,像播放器一样点击进度条的任意位置;
(程序员专用) less支持,类似linux系统的less命令,支持任意大小的文件,支持随时查看文件的任意位置,像播放器一样点击进度条的任意位置;
(程序员专用) tail支持,类似linux系统的tail命令,支持任意大小的文件;
支持细粒度的权限控制,能满足不同的权限需求;IT运维或者公司内部资料分享,允许控制文件可见和文件的各种操作。
支持全键盘操作,几乎所有操作均有对应的快捷键支持;
支持右键菜单,文件的常规操作都可以通过右键菜单完成;
支持文件重命名,点击选中文件,然后按F2即可重命名文件;
支持大文件上传,超大文件会自动分段上传,默认设置每次上传5M;
支持文件拖拽上传,可同时拖拽多个文件上传;
支持截图上传,截图之后按Ctrl + Shift + V;
支持音频和视频播放(需支持H5的浏览器);
体积小,只有不到3M,目前一般基于SSH的web应用,基本都在几十兆左右。Finder除了日志组件无任何第三方依赖(日志组件也不需要单独安装);
无数据库设计,免去部署数据库的麻烦,所有数据存储都存在本地文件系统,集群环境下分布式存储。
易于部署,直接扔到Tomcat里即可;
基于web的文件管理,几乎所有的操作系统和服务器的防火墙默认都对HTTP开放,而FTP大多需要专门开通;不需要用户安装专门的客户端软件,使用浏览器即可。
对网络环境无任何要求,不需要做任何特殊设置。出于安全考虑,几乎所有的服务器都限制单个HTTP请求体的大小,且默认值很小,一般在2M左右,并且限制连接时间。Finder不需要专门设置即可上传或者下载超大的文件,Finder所有的功能都使用短连接完成以避免服务器超时限制。对于大文件采用分片上传,一方面可以避免服务器的限制,另一方面在网络环境不好的情况下提高上传的成功率,因为大文件长时间连接一旦网络断掉就需要全部重传,Finder采用分片的方式,每次只上传一段数据,如果失败自动重新上传这一段,并且针对每一段都自动重试3次。
这个是类似less的效果图,采用拉模式实现,滚动文档将会根据当前文档位置自动拉取接下来的部分数据,并且绿色的进度条会实时显示当前显示的文档进度。下面绿色的进度条也可以直接点击定位到文件的某一个部分显示。文本区域只显示3000行数据,超过3000行将会自动清除。
下面是类似tail的效果,定时去服务器根据上次拉取的位置拉取尾部数据显示。
下面是音频播放器的效果:
下面是文件管理的效果,支持右键菜单,支持全键盘操作,支持拖拽上传文件,支持超大文件上传,支持多线程断点下载。
源码下载地址:
xuesong.java
浏览: 1039 次
来自: 北京
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'

我要回帖

更多关于 卫星实时监控地图 的文章

 

随机推荐