Linuxshell脚本 · 2022年11月7日 0

利用shell编写文件权限检测器

这里有个简单的需求,需要用shell脚本实现:

  • 检查/data/wwwroot/app目录下所有文件和目录,看是否满足下面条件:

  • 1)所有文件权限为644

  • 2)所有目录权限为755

  • 3)文件和目录所有者为www,所属组为root

  • 如果不满足,改成符合要求,注意,不要直接改权限,一定要有判断的过程。

这个需求并不算难,同样核心命令也是find,关键点在于如何判断。也许你想find出来之后直接修改权限或者修改所有者和所属组,但这是不符合要求的,因为你没有加判断。

先来看find的一个用法:

find  /dir  -type f  -perm 644

这样可以找到权限为644的文件,但需求中要求的是不为644的,那该怎么做呢?

这样做即可:

find  /dir  -type f  ! -perm 644

也就是加一个!  就达到目的了,也可以这样:

find  /dir  -type f  -not  -perm 644

同理,目录权限不是755,可以这样找:

find /dir  -type d -not  -perm  755

find也可以找所属组和所有者:

find  /dir  -group  root
find  /dir  -user root

除了使用find外,我们也可以使用stat命令来获取文件或者目录的权限、属主、属组,stat这样用:

查看文件权限:stat  -c  %a  1.txt
查看文件所属组:stat -c %G  1.txt
查看文件所有者:stat -c %U  1.txt

获取到权限后,再去做比对

p=`stat  -c  %a  1.txt`
if [ $p != '644' ]
then
    chmod 644 1.txt
fi

最终脚本如下:

#!/bin/bash
cd /data/wwwroot/app
for f in `find .`
do
    f_p=`stat -c %a f`
    f_u=`stat -c %Uf`
    f_g=`stat -c %G f`
    if [ -df ] 
    then
        [ f_p != '755' ] && chmod 755f
    else 
        [ f_p != '644' ] && chmod 644f
    fi
    [ f_u != 'www' ] && chown wwwf
    [ f_g != 'root' ] && chown :rootf
done

或者:

#!/bin/bash 
find /data/wwwroot/app/ -type d ! -prem 755 -exec chmod 755 {} \; 
find /data/wwwroot/app/ ! -type d ! -prem 644 -exec chmod 644 {} \;
find /data/wwwroot/app/ ! -user www -exec chown www {} \; 
find /data/wwwroot/app/ ! -group root -exec chgrp root {} \;

两个脚本相比,第一个只需要find一次,而第二个需要find四次,如果文件量很大,执行效率很差。