In der IT-Welt kann die Automatisierung von sich wiederholenden Aufgaben Zeit sparen und Fehler reduzieren. Eine solche Aufgabe ist die Überprüfung des Vorhandenseins bestimmter Dateien oder Ordner in mehreren Verzeichnissen. Ob für die Compliance, die Systemüberwachung oder die Fehlerbehebung, eine automatisierte Methode zur Überprüfung der Existenz von Dateien kann für IT-Experten und Managed Service Provider (MSPs) von unschätzbarem Wert sein. In diesem Blogbeitrag wird ein Bash-Skript vorgestellt, das diesen Prozess rationalisiert und für eine effiziente und zuverlässige Dateiverwaltung sorgt.
Kontext
Dieses Skript ist besonders nützlich für IT-Experten, die die Existenz wichtiger Dateien oder Ordner regelmäßig überprüfen müssen. Es bietet eine automatisierte Lösung zum Durchsuchen von Verzeichnissen, um sicherzustellen, dass wichtige Dateien vorhanden sind oder um zu erkennen, wenn sie fehlen. Diese Fähigkeit ist in verschiedenen Szenarien von entscheidender Bedeutung, z. B. bei der Überprüfung der Speicherorte von Backups, der Gewährleistung des Vorhandenseins von Konfigurationsdateien oder der Bestätigung der Bereitstellung kritischer Anwendungen.
Das Skript zur Überprüfung der Existenz von Dateien und Ordnern
#!/usr/bin/env bash
# Description: Alert if a specified file or folder is found in a directory or subdirectory you specify.
#
# Release Notes: Initial Release
# By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
# Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
# Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
# Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider.
# Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
# Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
# Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
# EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#
# Below are all the (case sensitive) valid parameters for this script.
# Only the path to search and name of file or folder are required!
#
# Parameter: --path "/opt/NinjaRMM/programdata"
# Required
# Base path to search for files or folders.
#
# Parameter: --name "ninjarmm-cli"
# Required
# Name of the file or folder to search for.
# Notes:
# If the name is not provided, the script will search for the path only.
# This is case sensitive and accepts wildcards.
#
# Parameter: --type "Files Or Folders"
# Required
# Search for files or folders.
#
# Parameter: --type "Files Only"
# Required
# Searches for files only.
#
# Parameter: --type "Folders Only"
# Required
# Searches for folder only.
#
# Parameter: --timeout 10
# Optional and defaults to 30 minutes
# Time in minutes to wait for the search to complete before timing out.
#
# Parameter: --customfield "myCustomField"
# Optional
# Custom Field to save the search results to.
die() {
local _ret="${2:-1}"
test "${_PRINT_HELP:-no}" = yes && print_help >&2
echo "$1" >&2
exit "${_ret}"
}
begins_with_short_option() {
local first_option all_short_options='h'
first_option="${1:0:1}"
test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0
}
# Initize arguments
_arg_path=
_arg_name=
_arg_type=
_arg_timeout=30
_arg_customfield=
print_help() {
printf '%s\n' "Check existence of a file or folder"
printf 'Usage: %s [--path <arg>] [--name <arg>] [--type <"Files Only"|"Folders Only"|"Files Or Folders">] [--timeout <30>] [--customfield <arg>] [-h|--help]\n' "$0"
printf '\t%s\n' "-h, --help: Prints help"
}
parse_commandline() {
while test $# -gt 0; do
_key="$1"
case "$_key" in
--path)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_path="$2"
shift
;;
--path=*)
_arg_path="${_key##--path=}"
;;
--name)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_name="$2"
shift
;;
--name=*)
_arg_name="${_key##--name=}"
;;
--type)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_type="$2"
shift
;;
--type=*)
_arg_type="${_key##--type=}"
;;
--timeout)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_timeout="$2"
shift
;;
--timeout=*)
_arg_timeout="${_key##--timeout=}"
;;
--customfield)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_customfield="$2"
shift
;;
--customfield=*)
_arg_customfield="${_key##--customfield=}"
;;
-h | --help)
print_help
exit 0
;;
-h*)
print_help
exit 0
;;
*)
_PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
;;
esac
shift
done
}
parse_commandline "$@"
function SetCustomField() {
customfieldName=$1
customfieldValue=$2
if [ -f "${NINJA_DATA_PATH}/ninjarmm-cli" ]; then
if [ -x "${NINJA_DATA_PATH}/ninjarmm-cli" ]; then
if "$NINJA_DATA_PATH"/ninjarmm-cli get "$customfieldName" >/dev/null; then
# check if the value is greater than 10000 characters
if [ ${#customfieldValue} -gt 10000 ]; then
echo "[Warn] Custom field value is greater than 10000 characters"
fi
if ! echo "${customfieldValue::10000}" | "$NINJA_DATA_PATH"/ninjarmm-cli set --stdin "$customfieldName"; then
echo "[Warn] Failed to set custom field"
else
echo "[Info] Custom field value set successfully"
fi
else
echo "[Warn] Custom Field ($customfieldName) does not exist or agent does not have permission to access it"
fi
else
echo "[Warn] ninjarmm-cli is not executable"
fi
else
echo "[Warn] ninjarmm-cli does not exist"
fi
}
if [ ! "$(command -v timeout)" ]; then
notimeout=true
# If the timeout command does not exist, create a function to mimic the timeout command
function timeout() { perl -e 'alarm shift; exec @ARGV' "$@"; }
fi
parentSearchPath=$_arg_path
leafSearchName=$_arg_name
searchType=$_arg_type
timeout=$_arg_timeout
customField=$_arg_customfield
# Get values from Script Variables
if [[ -n "${pathToSearch}" ]]; then
parentSearchPath="${pathToSearch}"
fi
if [[ -n "${nameOfFileOrFolder}" ]]; then
leafSearchName="${nameOfFileOrFolder}"
fi
if [[ -n "${filesOrFolders}" && "${filesOrFolders}" != "null" ]]; then
searchType="${filesOrFolders}"
fi
if [[ -n "${searchTimeout}" && "${searchTimeout}" != "null" ]]; then
timeout="${searchTimeout}"
fi
if [[ -n "${customFieldName}" && "${customFieldName}" != "null" ]]; then
customField="${customFieldName}"
fi
# Check if parentSearchPath is a link and replace it with the resolved path
if [ -L "${parentSearchPath}" ]; then
echo "[Info] Path to Search is a link: ${parentSearchPath} -> $(readlink -f "${parentSearchPath}")"
echo "[Info] Will use the resolved path to search"
parentSearchPath=$(readlink -f "${parentSearchPath}")
fi
if [[ -z "${parentSearchPath}" ]]; then
echo "[Error] Path to Search is empty"
exit 1
fi
# Check if path exists
if [ -e "${parentSearchPath}" ]; then
echo "[Info] Path ${parentSearchPath} exists"
else
echo "[Error] Path to Search ${parentSearchPath} does not exist or is an invalid path"
exit 1
fi
# Check if timeout is a number
if ! [[ "${timeout}" =~ ^[0-9]+$ ]]; then
echo "[Error] Timeout is not a number"
exit 1
fi
# Check if timeout is not in the range of 1 to 120
if [[ "${timeout}" -lt 1 || "${timeout}" -gt 120 ]]; then
echo "[Error] Timeout is not in the range of 1 to 120"
exit 1
fi
# Check if search type is valid
if $notimeout; then
# If the timeout command does not exist, convert the timeout to minutes
timeout=$((timeout * 60))
else
# If the timeout command does exist, add m to the end of the string
timeout="${timeout}m"
fi
if [[ $OSTYPE == 'darwin'* ]]; then
if ! plutil -lint /Library/Preferences/com.apple.TimeMachine.plist >/dev/null; then
echo "This script requires ninjarmm-macagent to have Full Disk Access."
echo "Add ninjarmm-macagent to the Full Disk Access list in System Preferences > Security & Privacy, quit the app, and re-run this script."
exit 1
fi
fi
# Search for files or folders
if [[ -n "${leafSearchName}" && "${leafSearchName}" != "null" ]]; then
if [[ "${searchType}" == *"Files"* && "${searchType}" == *"Only"* ]]; then
echo "[Info] Searching for files only"
# Search for files only
# Use timeout to prevent the find command from running indefinitely
foundPath=$(timeout "${timeout}" find "$parentSearchPath" -type f -name "$leafSearchName" 2>/dev/null)
exitcode=$?
if [[ $exitcode -eq 0 || $exitcode -eq 124 ]]; then
if [[ -n $foundPath ]]; then
echo "[Alert] File Found"
fi
fi
elif [[ "${searchType}" == *"Folders"* && "${searchType}" == *"Only"* ]]; then
echo "[Info] Searching for folders only"
# Search for folders only
# Use timeout to prevent the find command from running indefinitely
foundPath=$(timeout "${timeout}" find "$parentSearchPath" -type d -name "$leafSearchName" 2>/dev/null)
exitcode=$?
if [[ $exitcode -eq 0 || $exitcode -eq 124 ]]; then
if [[ -n $foundPath ]]; then
echo "[Alert] File Found"
fi
fi
elif [[ "${searchType}" == *"Files"* && "${searchType}" == *"Folders"* ]]; then
echo "[Info] Searching for files or folders"
# Search for files or folders
# Use timeout to prevent the find command from running indefinitely
foundPath=$(timeout "${timeout}" find "$parentSearchPath" -name "$leafSearchName" 2>/dev/null)
exitcode=$?
if [[ $exitcode -eq 0 || $exitcode -eq 124 ]]; then
if [[ -n $foundPath ]]; then
echo "[Alert] File Found"
fi
fi
else
echo "[Error] Invalid search type"
echo "Valid search types: Files Only, Folders Only, Files Or Folders"
exit 1
fi
elif [[ -z "${leafSearchName}" ]]; then
echo "[Info] Searching in path only"
# Search in path only
# Use timeout to prevent the find command from running indefinitely
foundPath=$(timeout "${timeout}" find "$parentSearchPath")
exitcode=$?
if [[ $exitcode -eq 0 || $exitcode -eq 124 ]]; then
if [[ -n $foundPath ]]; then
echo "[Alert] File Found"
fi
fi
fi
# Check exit code
if [[ -n $foundPath ]]; then
# Split the string into an array
IFS=$'\n' read -rd '' -a foundPathArray <<<"${foundPath}"
# Print each element of the array
for element in "${foundPathArray[@]}"; do
echo "[Alert] ${element} exists"
done
elif [[ -z $foundPath ]]; then
echo "[Warn] Could not find a file or folder"
exit 1
else
# If the find command fails to find the file or folder
# Figure out the grammer for the search type
if [[ "${searchType}" == *"Only"* ]]; then
if [[ "${searchType}" == *"Files"* ]]; then
searchTypeInfo="file"
elif [[ "${searchType}" == *"Folders"* ]]; then
searchTypeInfo="folder"
fi
elif [[ "${searchType}" == *"Files"* && "${searchType}" == *"Folders"* ]]; then
searchTypeInfo="file or folder"
fi
echo "[Info] Could not find a ${searchTypeInfo} in the path ${parentSearchPath} with the name containing: ${leafSearchName}"
fi
# If foundPath contains "Alarm clock:" then the command timed out
if [[ "${foundPath}" == *"Alarm clock:"* ]]; then
echo "[Alert] Timed out searching for file or folder"
# Remove "Alarm clock: *" from the string
foundPath=${foundPath/Alarm clock: [0-9]*//}
fi
# If command times out
if [[ $exitcode -ge 124 && $exitcode -le 127 || $exitcode -eq 137 ]]; then
echo "[Alert] Timed out searching for file or folder"
echo "timeout exit code: $exitcode"
echo " 124 if COMMAND times out, and --preserve-status is not specified"
echo " 125 if the timeout command itself fails"
echo " 126 if COMMAND is found but cannot be invoked"
echo " 127 if COMMAND cannot be found"
echo " 137 if COMMAND (or timeout itself) is sent the KILL (9) signal (128+9)"
echo "find command result: $foundPath"
exit 1
fi
# Save to custom field
if [[ -n "${customField}" && "${customField}" != "null" ]]; then
SetCustomField "${customField}" "${foundPath}"
fi
Greifen Sie auf über 300 Skripte im NinjaOne Dojo zu.
Detailansicht
Das Skript arbeitet mit mehreren Parametern, mit denen der Suchprozess angepasst werden kann. Hier finden Sie eine detaillierte Aufschlüsselung der Funktionen:
1. Parameter und Initialisierung:
- –path: Gibt das Basisverzeichnis an, in dem gesucht werden soll.
- –name: Legt den Namen der Datei oder des Ordners fest, nach dem gesucht werden soll, wobei Wildcard-Zeichen unterstützt werden.
- –type: Legt fest, ob nach Dateien, Ordnern oder beidem gesucht werden soll.
- –timeout: Legt die maximale Zeit für den Suchvorgang fest. Die Standardeinstellung ist 30 Minuten.
- –customfield: Ermöglicht das Speichern des Suchergebnisses in einem benutzerdefinierten Feld.
2. Argumente-Parsen: Das Skript parst die Befehlszeilenargumente, um die Suchparameter zu initialisieren. Fehlt ein erforderlicher Parameter, wird eine Fehlermeldung ausgegeben und das Skript beendet sich.
3. Ausführung der Suche:
- Das Skript löst alle symbolischen Links im Suchpfad auf.
- Es wird überprüft, ob der angegebene Pfad existiert und gültig ist.
- Das Skript stellt sicher, dass die Zeitüberschreitung innerhalb des zulässigen Bereichs liegt (1 bis 120 Minuten).
4. Datei- oder Ordnersuche: Je nach dem angegebenen Typ (Dateien, Ordner oder beides) verwendet das Skript den Befehl ‚find‘ mit einer Zeitüberschreitung, um die gewünschten Elemente zu finden. Wenn es gefunden wird, werden die Benutzer:innen benachrichtigt und das Ergebnis optional in einem benutzerdefinierten Feld gespeichert.
5. Fehlerbehandlung und Berichterstattung: Das Skript enthält eine umfassende Fehlerbehandlung, die dafür sorgt, dass Probleme wie ungültige Pfade, falsche Timeout-Werte oder nicht existierende Dateien bzw. Ordner den Benutzer:innen deutlich mitgeteilt werden.
Potenzielle Anwendungsfälle
Fallstudie: Überprüfung der IT-Compliance
Ein IT-Experte ist dafür verantwortlich, dass auf allen Servern wichtige Sicherheitskonfigurationsdateien vorhanden sind. Mit diesem Skript kann er den Überprüfungsprozess automatisieren:
1. Einrichtung:
- –path: /etc/security
- –name: security.conf
- –type: Files Only
- –timeout: 10
2. Ausführung: Das Skript sucht innerhalb der eingestellten Zeitspanne im angegebenen Pfad nach der Datei ’security.conf‘. Wenn sie gefunden wird, protokolliert das Skript eine Warnmeldung; wenn nicht, benachrichtigt es den IT-Experten und ermöglicht so eine schnelle Problemlösung.
Vergleiche
Im Vergleich zur manuellen Überprüfung oder zur Verwendung einfacher Shell-Befehle bietet dieses Skript mehrere Vorteile:
- Automatisierung: Reduziert den Bedarf an manuellen Kontrollen.
- Timeout-Management: Verhindert längere Suchvorgänge durch die Durchsetzung eines Zeitüberschreitungswertes.
- Benutzerdefinierte Berichterstellung: Ermöglicht die Speicherung von Ergebnissen in benutzerdefinierten Feldern für die weitere Verarbeitung oder die Erstellung von Compliance-Berichten.
Andere Methoden, wie z. B. die Verwendung von ‚ls‘ oder Testbefehlen in der Bash, verfügen nicht über diese erweiterten Funktionen, sodass dieses Skript eine robustere und effizientere Lösung darstellt.
FAQs
- Was passiert, wenn das Skript eine Zeitüberschreitung aufweist?
Das Skript meldet eine Zeitüberschreitung und beendet sich mit einem entsprechenden Fehlercode, damit die Benutzer:innen wissen, dass die Suche unvollständig war. - Kann ich nach mehreren Dateitypen gleichzeitig suchen?
Nein, das Skript unterstützt derzeit die Suche nach Dateien oder Ordnern auf der Grundlage eines einzigen Namensmusters zur gleichen Zeit. - Wie gehe ich mit symbolischen Links im Suchpfad um?
Das Skript löst automatisch symbolische Links auf und stellt sicher, dass die Suche im richtigen Verzeichnis durchgeführt wird.
Folgen
Mit diesem Skript kann die IT-Sicherheit erheblich verbessert werden, indem man sicherstellt, dass wichtige Dateien und Ordner vorhanden sind. Die automatische Überprüfung trägt zur Einhaltung von Sicherheitsrichtlinien bei und minimiert das Risiko, dass wichtige Dateien fehlen, was zu Systemschwachstellen oder -ausfällen führen könnte.
Empfehlungen
- Regelmäßige Audits: Planen Sie die regelmäßige Ausführung des Skripts, um die aktuelle Überprüfung kritischer Dateien aufrechtzuerhalten.
- Verwendung benutzerdefinierter Felder: Nutzen Sie die Option für benutzerdefinierte Felder, um Suchergebnisse systematisch zu verfolgen und zu melden.
- Timeout-Einstellungen: Passen Sie den Timeout-Parameter auf der Grundlage der erwarteten Größe des Verzeichnisses und der Systemleistung an, um unnötige Verzögerungen zu vermeiden.
Abschließende Überlegungen
Dieses Bash-Skript ist ein leistungsfähiges Tool für IT-Experten, das eine automatisierte und zuverlässige Methode zur Überprüfung der Existenz von Dateien und Ordnern bietet. Durch die Integration dieses Skripts in Routinekontrollen können MSPs eine höhere Effizienz und Sicherheit in ihrem Betrieb gewährleisten. Mit Tools wie NinjaOne lässt sich dieser Prozess weiter verbessern, indem sie umfassende IT-Management-Lösungen anbieten, die die Bereitstellung, Überwachung und Verwaltung von Skripten über mehrere Systeme hinweg erleichtern.
Die Automatisierung der Dateiverwaltung spart nicht nur Zeit, sondern erhöht auch die Genauigkeit und sorgt dafür, dass wichtige Dateien immer dort sind, wo sie sein müssen.