1
0
Fork 1
swap-increase/pull-logs.sh

92 lines
2.8 KiB
Bash

#!/bin/bash
# Check if correct number of arguments are passed
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <target-date> <target-time> <time-range>"
echo "Example: $0 2024-09-28 11:35 5"
echo "The time range is in minutes."
exit 1
fi
TARGET_DATE=$1
TARGET_TIME=$2
RANGE=$3
# Combine date and time for start and end times in ISO 8601 format
START=$(date -d "$TARGET_DATE $TARGET_TIME - $RANGE minutes" +"%Y-%m-%d %H:%M:%S")
END=$(date -d "$TARGET_DATE $TARGET_TIME + $RANGE minutes" +"%Y-%m-%d %H:%M:%S")
# Debugging output to ensure correct start and end times
echo "START: $START"
echo "END: $END"
# Ensure that START is before END
if [[ $(date -d "$START" +%s) -ge $(date -d "$END" +%s) ]]; then
echo "Error: START time is greater than or equal to END time."
exit 1
fi
echo "Collecting logs from $START to $END"
# Function to check journalctl logs
get_journalctl_logs() {
if command -v journalctl &> /dev/null; then
echo "----- Journalctl Logs -----"
journalctl --since="$START" --until="$END"
else
echo "journalctl not found, skipping..."
fi
}
# Function to check logs in /var/log
get_var_log_logs() {
echo "----- /var/log Logs -----"
log_files=(/var/log/syslog /var/log/auth.log /var/log/kern.log /var/log/dmesg)
for log in "${log_files[@]}"; do
if [[ -f $log ]]; then
echo "Logs from $log"
awk -v start="$START" -v end="$END" '{
logtime = $1 " " $2 " " $3
logtime_epoch = mktime(gensub(/-|:/, " ", "g", logtime))
start_epoch = mktime(gensub(/-|:/, " ", "g", start))
end_epoch = mktime(gensub(/-|:/, " ", "g", end))
if (logtime_epoch >= start_epoch && logtime_epoch <= end_epoch) {
print $0
}
}' $log
else
echo "$log not found, skipping..."
fi
done
}
# Function to check logs of specific services like nginx or apache2
get_service_logs() {
echo "----- Service Logs (nginx, apache, mysql, etc.) -----"
service_logs=(/var/log/nginx/access.log /var/log/nginx/error.log /var/log/apache2/access.log /var/log/mysql/error.log)
for log in "${service_logs[@]}"; do
if [[ -f $log ]]; then
echo "Logs from $log"
awk -v start="$START" -v end="$END" '{
logtime = $1 " " $2
logtime_epoch = mktime(gensub(/-|:/, " ", "g", logtime))
start_epoch = mktime(gensub(/-|:/, " ", "g", start))
end_epoch = mktime(gensub(/-|:/, " ", "g", end))
if (logtime_epoch >= start_epoch && logtime_epoch <= end_epoch) {
print $0
}
}' $log
else
echo "$log not found, skipping..."
fi
done
}
# Fetch logs
get_journalctl_logs
get_var_log_logs
get_service_logs