Useful CLI tools (bash) for Arch Linux administration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

331 lines
10 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. #!/usr/bin/env bash
  2. #
  3. # nowner - Find orphan files on various Linux distributions
  4. #
  5. # Copyright (C) 2021 Pekka Helenius <pekka.helenius@fjordtek.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #####################################
  20. bash_yellow=$'\033[93m'
  21. bash_red=$'\033[91m'
  22. bash_color_default=$'\033[0m'
  23. PACMAN_EXEC="/usr/bin/pacman"
  24. #####################################
  25. #Useful for additional commands:
  26. # TODO: Look for .old .bak ~ .pacnew and such files (maybe separate command or not??)
  27. #find /usr/share -maxdepth 1 -type d -exec stat --format "%n: %U" {} \; | grep fincer
  28. #####################################
  29. # Check for command dependencies
  30. if [[ $(which --help 2>/dev/null) ]] && [[ $(echo --help 2>/dev/null) ]]; then
  31. COMMANDS=(who awk getent printenv sed file stat id date find tee chown timedatectl hostname)
  32. a=0
  33. for command in ${COMMANDS[@]}; do
  34. if [[ ! $(which $command 2>/dev/null) ]]; then
  35. COMMANDS_NOTFOUND[$a]=$command
  36. let a++
  37. fi
  38. done
  39. if [[ -n $COMMANDS_NOTFOUND ]]; then
  40. echo -e "\n${bash_red}Error:${bash_color_default} The following commands could not be found: ${COMMANDS_NOTFOUND[*]}\nAborting\ņ"
  41. exit 1
  42. fi
  43. else
  44. exit 1
  45. fi
  46. #####################################
  47. # Retrieve our Linux distribution and set the correct
  48. # package manager for this command
  49. # Get our Linux distribution
  50. DISTRO=$(cat /etc/os-release | sed -n '/PRETTY_NAME/p' | grep -o '".*"' | sed -e 's/"//g' -e s/'([^)]*)'/''/g -e 's/ .*//' -e 's/[ \t]*$//')
  51. function check_pkgmgr() {
  52. if [[ ! $(which $1 2>/dev/null) ]]; then
  53. echo -e "\n${bash_red}Error:${bash_color_default} Package manager ($1) could not be found\nAborting\ņ"
  54. exit 1
  55. fi
  56. }
  57. #####################################
  58. # Arch Linux
  59. if [[ $DISTRO == "Arch" ]]; then
  60. check_pkgmgr pacman
  61. function PKGMGR_CMD() { ${PACMAN_EXEC} -Qo "$1" &>/dev/null || echo "error" | wc -l ; }
  62. fi
  63. # Debian, Ubuntu
  64. if [[ $DISTRO == "Ubuntu" ]] || [[ $DISTRO == "Debian" ]]; then
  65. check_pkgmgr dpkg
  66. function PKGMGR_CMD() { dpkg -S "$1" &>/dev/null || echo "no path found matching pattern" | wc -l ; }
  67. fi
  68. # CentOS
  69. # TODO
  70. # Fedora
  71. # TODO
  72. # RedHat
  73. # TODO
  74. # OpenSUSE
  75. # TODO
  76. #####################################
  77. # List files and directories which are not owned by any package in the system
  78. echo -e "\nSearch for files & folders which are not owned by any installed package.\n"
  79. # Avoid storing log files into root home
  80. REAL_USER=$(who am i | awk '{print $1}')
  81. REAL_USER_HOME=$(getent passwd $REAL_USER | cut -d: -f6)
  82. if [[ $# -eq 0 ]]; then
  83. read -r -p "Folder path: " BASEDIR
  84. #Substitute $ symbol from environmental variables for printenv input
  85. if [[ $BASEDIR == *"$"* ]]; then
  86. BASEDIR=$(echo $(printenv $(echo ${BASEDIR} | sed 's/\$//g')))
  87. fi
  88. else
  89. BASEDIR=$1
  90. fi
  91. if [[ ! $(file --mime-type "${BASEDIR}" | grep "inode/directory" | wc -l) -eq 1 ]]; then
  92. echo "${bash_red}Error:${bash_color_default} Use full folder path as an input value!"
  93. elif [[ $# -gt 1 ]]; then
  94. echo "${bash_red}Error:${bash_color_default} Only one argument accepted!"
  95. else
  96. echo -e "Search depth:\n1 = "${BASEDIR}"\n2 = "${BASEDIR}" & subfolders\n3 = "${BASEDIR}", subfolders & 2 folder levels below\n4 = no limit\n"
  97. read -r -p "Which depth value you prefer? [Default: 1] " response
  98. case $response in
  99. 1)
  100. depth="-maxdepth 1 "
  101. depthstr="${BASEDIR}"
  102. DEPTH_NUM=1
  103. ;;
  104. 2)
  105. depth="-maxdepth 2 "
  106. depthstr="${BASEDIR} and subfolders"
  107. DEPTH_NUM=2
  108. ;;
  109. 3)
  110. depth="-maxdepth 3 "
  111. depthstr="${BASEDIR}, subfolders and 2 folder levels below"
  112. DEPTH_NUM=3
  113. ;;
  114. 4)
  115. depth=""
  116. depthstr="${BASEDIR} and all subfolders"
  117. DEPTH_NUM=4
  118. ;;
  119. *)
  120. echo -e "\nUsing default value [1]"
  121. depth="-maxdepth 1 "
  122. depthstr="${BASEDIR}"
  123. DEPTH_NUM=1
  124. esac
  125. unset response
  126. #####################################
  127. BASEDIR_OWNER=$(stat --format "%u" "${BASEDIR}")
  128. if [[ $BASEDIR_OWNER -eq 0 ]] && [[ $(id -u) -ne 0 ]]; then
  129. echo -e "\n${bash_yellow}Warning:${bash_color_default} the main folder '${BASEDIR}' is owned by root. Some files or directories may be inaccessible. Please consider running this command with root privileges.\n"
  130. read -r -p "Continue? [Y/n] " response
  131. if [[ $(echo $response | sed 's/ //g') =~ ^([nN][oO]|[nN])$ ]]; then
  132. echo -e "\nAborting\n"
  133. exit 0
  134. fi
  135. elif [[ $BASEDIR_OWNER -ne $(id -u $REAL_USER) ]] && [[ $BASEDIR_OWNER -ne 0 ]]; then
  136. echo -e "\n${bash_yellow}Warning:${bash_color_default} the main folder belongs to local user '$(id -un $BASEDIR_OWNER)'. Some files or directories may be inaccessible\n"
  137. fi
  138. #####################################
  139. BASEDIR_UNDERLINE="$(echo ${BASEDIR} | sed 's/\//_/g')"
  140. LOGFILE="$REAL_USER_HOME/nowner-${BASEDIR_UNDERLINE}-depth-${DEPTH_NUM}_$(date +%Y-%m-%d).log"
  141. # Delete log file if the command is interrupted
  142. # Define function del_log here, after we have defined $LOGFILE
  143. #
  144. # Interrupt signal must be trapped after $LOGFILE and before any further commands
  145. # That's why it is located here and not at the end or at the start of this script
  146. #
  147. del_log() { rm $LOGFILE ; exit 0 ; }
  148. trap 'del_log' INT
  149. read -r -p "Save results to a file? [Y/n] " response
  150. if [[ $(echo $response | sed 's/ //g') =~ ^([yY][eE][sS]|[yY])$ ]]; then
  151. echo -e "Scan results will be saved in '$LOGFILE'"
  152. TO_FILE=1
  153. else
  154. TO_FILE=0
  155. fi
  156. #####################################
  157. echo -e "\nSearching unowned files & folders in $depthstr\n"
  158. #####################################
  159. function data_counter() {
  160. i=0
  161. n=1
  162. ARRAY=("$@")
  163. COUNT=${#ARRAY[@]}
  164. for scan_data in "${ARRAY[@]}"; do
  165. echo -ne "Scanning $data_name $n ($(( 100*$n/$COUNT ))%) of all $type ($COUNT) in $depthstr\r"
  166. if [[ $(PKGMGR_CMD $scan_data) -eq 1 ]]; then
  167. DATA_ARRAY[$i]="$(( $i + 1 )) - ${scan_data}"
  168. let i++
  169. fi
  170. let n++
  171. done
  172. ###############
  173. function results() {
  174. if [[ $i -gt 0 ]]; then
  175. echo -e "\nThe following $i of $COUNT $type is not owned by any installed package in $depthstr:\n"
  176. IFS=$'\n'
  177. echo -e "${DATA_ARRAY[*]}\n"
  178. unset IFS
  179. unset DATA_ARRAY
  180. elif [[ "$COUNT" -eq 0 ]]; then
  181. echo -e "\nCouldn't find any $type in the target path $depthstr. Consider using greater depth value.\n"
  182. else
  183. echo -e "\nAll $type are owned by system packages in $depthstr"
  184. fi
  185. }
  186. if [[ $TO_FILE -eq 1 ]]; then
  187. results | tee -a $LOGFILE
  188. echo ""
  189. else
  190. results
  191. echo ""
  192. fi
  193. }
  194. #####################################
  195. function data_check() {
  196. DATASET=$(find "${BASEDIR}" ${depth} ${1} 2>/dev/null)
  197. IFS=$'\n'
  198. datacnt=0
  199. for DATA in ${DATASET}; do
  200. # Do read permission check for files/folders unless we are root
  201. #
  202. if [[ $(id -u) -ne 0 ]]; then
  203. echo -e "Checking for $2 permissions. Please wait\n"
  204. DATA_OWNER=$(stat --format "%u" "${DATA}")
  205. DATA_OWNER_HUMAN=$(stat --format "%U" "${DATA}")
  206. # If the current user (which this command is executed by) is not the owner of folder/file
  207. # By performing this check we can distinguish whether the user
  208. # belongs to the owner class or "others" class
  209. # and therefore we can perform check for "read" bit
  210. # for "others" if needed
  211. #
  212. if [[ $(id -u) -ne $DATA_OWNER ]]; then
  213. # If read bit is defined for "others"
  214. if [[ $(stat --format "%A" "${DATA}" | cut -c 8) == "r" ]]; then
  215. VALID_DATASET[$datacnt]="${DATA}"
  216. let datacnt++
  217. else
  218. echo -e "${bash_yellow}Warning:${bash_color_default} $data_name '${DATA}' (owned by $DATA_OWNER_HUMAN) is not readable. Skipping it\n"
  219. fi
  220. # We assume that the file/dir owner has read permission for this specific file/folder
  221. #
  222. else #elif [[ $(id -u $REAL_USER) -eq $DATA_OWNER ]]; then
  223. VALID_DATASET[$datacnt]="${DATA}"
  224. let datacnt++
  225. fi
  226. else
  227. VALID_DATASET[$datacnt]="${DATA}"
  228. let datacnt++
  229. fi
  230. done
  231. unset IFS
  232. unset datacnt
  233. data_counter "${VALID_DATASET[@]}"
  234. unset VALID_DATASET
  235. }
  236. #####################################
  237. function folders() {
  238. type="folders"
  239. data_name="folder"
  240. find_type="-mindepth 1 -type d"
  241. data_check "${find_type}" $data_name
  242. }
  243. function files() {
  244. type="files"
  245. data_name="file"
  246. find_type="-type f"
  247. data_check "${find_type}" $data_name
  248. }
  249. #####################################
  250. if [[ $TO_FILE -eq 1 ]]; then
  251. echo -e "Log timestamp: $(date '+%d-%m-%Y, %X') (TZ: $(timedatectl status | grep "Time zone:" | awk '{print $3}'))\nComputer: $(hostname)\nScanning Depth: $depthstr" >> $LOGFILE
  252. fi
  253. folders
  254. files
  255. if [[ $TO_FILE -eq 1 ]]; then
  256. chown $REAL_USER $LOGFILE
  257. echo -e "Scan complete. Results have been saved in '$LOGFILE'\n"
  258. else
  259. echo -e "Scan complete\n"
  260. fi
  261. fi