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.

328 lines
10 KiB

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