use*_*327 13 filesystem command-line bash scripts inotify
我知道已经有一些关于类似主题的讨论。但这就是我基本上想要做的。
我有一个名为 watch 的目录watched
,每当将文件添加到该目录时,我想触发一个名为的脚本syncbh.sh
,该脚本将从该目录中取出文件并将它们上传到远程服务器。
需要注意的是,文件是watched
由一个用户 (user2)在目录中创建的,但脚本由另一个用户 (user1) 执行。
我已经尝试使用incron来完成此操作,但一直遇到一个主要问题,因为虽然该脚本可以由具有 root 权限的 user1 手动执行,但实际上incron守护进程从未被其他 user2 的文件创建事件自动触发。
我已经考虑过inoticoming是否是更好的选择,但我不清楚它的语法是如何工作的。如果有更好的方法来实现这一点,或者如果我最终使用inocoming命令语法是什么,如果在该目录中创建/修改了文件,则要求它监视/home/user1/watched
目录并执行脚本/usr/local/bin/syncbh.sh
?
任何帮助将非常感激。
使用inoticoming
:
您可以将在启动时/etc/init.d/
运行的脚本放入其中inoticoming
。
创建一个新的文件夹来保存inoticoming
日志/最后pid
的watched
文件夹:sudo mkdir -p /var/log/inoticoming/watched/
创建一个脚本inoticoming_watched
在/etc/init.d/
:
* 记得修改 <path_to_folder> 和 <path_to_script> 以匹配watched
文件夹的完整路径和要执行的脚本的完整路径
#!/bin/sh
case "${1}" in
start)
inoticoming --logfile '/var/log/inoticoming/watched/inoticoming.log' --pid-file '/var/log/inoticoming/watched/inoticoming_last_pid.txt' <path_to_folder> <path_to_script> \;
;;
stop)
kill -15 $(< /var/log/inoticoming/watched/inoticoming_last_pid.txt tee)
;;
restart)
${0} stop
sleep 1
${0} start
;;
*)
echo "Usage: ${0} {start|stop|restart}"
exit 1
;;
esac
Run Code Online (Sandbox Code Playgroud)
将脚本标记为可执行: sudo chmod u+x /etc/init.d/inoticoming_watched
确保调用的脚本inoticoming_watched
是可执行的。
更新rc.d
以使服务inoticoming_watched
在启动时启动:sudo update-rc.d inoticoming_watched defaults
您可以查看inoticoming
登录信息/var/log/inoticoming/watched
。
首先,安装inoticoming:
sudo apt-get install inoticoming
Run Code Online (Sandbox Code Playgroud)
然后使用这个命令:
请注意正在进行的 inoticoming 进程,因为它们可以启动多次。
$ inoticoming /home/user1/watched /usr/local/bin/syncbh.sh /home/user1/watched/{} \;
^ ^ ^
| | |
^-- The directory to be monitored |
| |
^-- Your script |
^-- The parameter for your script
Run Code Online (Sandbox Code Playgroud)
该进程在后台运行并正在监视/home/user1/watched
当在该目录中添加或更改文件时,/usr/local/bin/syncbh.sh
将调用该脚本。
此脚本的参数在本例中为/home/user1/watched/<name_of_changed_or_modified_file>
{}
被文件名替换
May*_*hux -2
首先,一个监视watched
目录的脚本:
#! /bin/bash
folder=/path-to-watched
inotifywait -m -q -e create -e modify '%:e %w%f' $folder | while read file
do
#make the sync here
done
Run Code Online (Sandbox Code Playgroud)
其次要作为另一个用户(user2)进行同步:
sudo -H -u user2 bash -c 'sh /usr/local/bin/syncbh.sh '
Run Code Online (Sandbox Code Playgroud)
现在,为了不出现用户提示,您可以sudo
在文件中设置密码,并在需要时从该文件中读取密码(注意您必须使用-S
withsudo
从文件中获取密码)。
把你的sudo
密码放在一个文件中,假设passwd.txt
,那么上面的命令就会很糟糕
sudo -S -H -u user2 bash -c 'sh /usr/local/bin/syncbh.sh ' < /path-to/passwd.txt
Run Code Online (Sandbox Code Playgroud)
现在整体脚本将如下所示:
#! /bin/bash
folder=/path-to-watched
inotifywait -m -q -e create -e modify '%:e %w%f' $folder | while read file
do
sudo -S -H -u user2 bash -c 'sh /usr/local/bin/syncbh.sh ' < /path-to/passwd.txt
done
Run Code Online (Sandbox Code Playgroud)