Home » Questions » Computers [ Ask a new question ]

How can I find only the executable files under a certain directory in Linux?

How can I find only the executable files under a certain directory in Linux?

How can I find only the executable files under a certain directory in Linux?

Asked by: Guest | Views: 418
Total answers/comments: 3
Guest [Entry]

"I know the question specifically mentions Linux, but since it's the first result on Google, I just wanted to add the answer I was looking for (for example if you are - like me at the moment - forced by your employer to use a non GNU/Linux system).

Tested on macOS 10.12.5

find . -perm +111 -type f"
Guest [Entry]

"As a fan of the one liner...

find /usr/bin -executable -type f -print0 | xargs file | grep ASCII

Using 'xargs' to take the output from the find command (using print0 to ensure filenames with spaces are handled correctly). We now have a list of files that are executable and we provide them, one by one, as the parameter for the 'file' command. Then grep for the term ASCII to ignore binaries. Please substitute -executable in find command with what style you prefer (see earlier answers) or what works on your 'NIX OS

I required the above to find files with eval in scripts owned by root, so created the following to help find priv escalation weaknesses where root user runs scripts with unsafe parameters...

echo -n ""+ Identifying script files owned by root that execute and have an eval in them...""
find / -not \( -path /proc -prune \) -type f -executable -user root -exec grep -l eval {} \; -exec file {} \; | grep ASCII| cut -d ':' -f1 > $outputDir""/root_owned_scripts_with_eval.out"" 2>/dev/null &"
Guest [Entry]

"I created a function in ~/.bashrc tonight to find executable files not in the system path and not directories:

# Quickly locate executables not in the path
xlocate () {
locate -0r ""$1"" | xargs -0 -I{} bash -c '[[ -x ""$1"" ]] && [[ ! -d ""$1"" ]] \
&& echo ""executable: $1""' _ {}
} # xlocate ()

The advantage is it will search three Linux distros and a Windows installation in under a second where the find command takes 15 minutes.

For example:

$ time xlocate llocate
executable: /bin/ntfsfallocate
executable: /home/rick/restore/mnt/e/bin/llocate
executable: /mnt/clone/bin/ntfsfallocate
executable: /mnt/clone/home/rick/restore/mnt/e/bin/llocate
executable: /mnt/clone/usr/bin/fallocate
executable: /mnt/e/bin/llocate
executable: /mnt/old/bin/ntfsfallocate
executable: /mnt/old/usr/bin/fallocate
executable: /usr/bin/fallocate

real 0m0.504s
user 0m0.487s
sys 0m0.018s

Or for a whole directory and all it's subs:

$ time xlocate /mnt/e/usr/local/bin/ | wc -l
65

real 0m0.741s
user 0m0.705s
sys 0m0.032s"