Ayr*_*rat 4 permissions bash scripts chmod
天上掉馅饼:您是否有一个脚本可以对系统中所有实际上无法执行的可执行文件执行 chmod -x (即,它们错误地具有x
标志)?
(上下文:
将备份文件从 NTFS 复制到 ext4 后,文件变为可执行文件(html、md、txt 等)。我想让文件不可执行,但只有那些真正不可执行的文件。我可能必须编写遍历系统中所有文件的脚本(例如for f in ``find /path``; do intelligent_chmod -x $f; done;
,intelligent_chmod
必须查看文件并确定它是 ELF 还是第一行!#...
等)
Joh*_*024 11
这用于find
查找设置了可执行位的常规文件。然后用file
命令测试它们,看看它们是否真的是可执行文件。如果没有,我们就运行chmod a-x
它们:
find . -type f -executable \( -exec sh -c 'file -b "$1" | grep -q executable' Test {} \; -o -exec chmod a-x {} \; \)
Run Code Online (Sandbox Code Playgroud)
如您所见,此find
命令有两个-exec
表达式,它们与逻辑或运算符相连。
-type f -executable
这告诉 find 只查找设置了可执行位的常规文件。
\(
这开始了一个小组。
默认情况下,find
条件是 AND 结合在一起的,AND 绑定比 OR 更紧密。在这种情况下,我们只想将以下两个-exec
命令与 OR绑定在一起。为此,我们需要一个小组。
-exec sh -c 'file -b "$1" | grep -q executable' Test {} \;
这让file
程序检查每个文件并grep
检查字符串executable
是否在file
命令的输出中。
在上面,Test
用作脚本的程序名称 ( $0
) sh -c
。(有关的讨论$0
和sh -c
,看到这个问题。)
以下是该file
命令的一些示例输出:
$ file -b bash
ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=0e188133c8cc5187e22eabd27cbcf46f32060fe3, stripped
$ file -b which
POSIX shell script, ASCII text executable
Run Code Online (Sandbox Code Playgroud)
如您所见,file
它足够聪明,不仅可以将 ELF 文件识别为可执行文件,还可以将各种脚本文件识别为可执行文件。
-o
这是逻辑或。这意味着只有在file
未将文件标识为可执行文件时才会执行后面的命令。
-exec chmod a-x {} \;
这将删除可执行位。
\)
这告诉find
我们已经到达分组命令的末尾。
如 中所述man magic
,该程序file
通过检查文件中的字符串来工作。许多文件都有非常独特的字符串。例如,一个 ELF 可执行文件以十六进制字符开头7f 45 4c 46
。Jpeg 和 png 图形具有类似的不同标记。 file
不会完全解析或分析文件,因此,对于某些文件,魔术失败了。正如 Ayrat 在评论中指出的那样,file
误解了以下内容:
$ cat tmp.py
Now is the time for all good men
to come to the aid of the party.
from xxx import yyy
$ file tmp.py
tmp.py: Python script, ASCII text executable
Run Code Online (Sandbox Code Playgroud)