Created
August 10, 2023 18:11
-
-
Save gkuba/8d8d1cb9841fbb2c22c76c4395237527 to your computer and use it in GitHub Desktop.
Runs traceroute against a list of IP's and saves the results to traceroute_results.txt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Output file for traceroute results | |
output_file="traceroute_results.txt" | |
# Function to run traceroute and save results | |
run_traceroute() { | |
local ip="$1" | |
local output=$(traceroute -n "$ip") | |
echo -e "\n-------------------------------------" | |
echo " Traceroute for $ip:" | |
echo -e "-------------------------------------\n" | |
echo "$output" | |
echo -e "\n-------------------------------------" >> "$output_file" | |
echo " Traceroute for $ip: " >> "$output_file" | |
echo -e "-------------------------------------\n" >> "$output_file" | |
echo "$output" >> "$output_file" | |
} | |
# Clear existing content in the output file | |
> "$output_file" | |
# Check if IP is valid | |
is_valid_ip() { | |
local ip="$1" | |
local valid_ip_pattern="^([0-9]{1,3}\.){3}[0-9]{1,3}$" | |
if [[ $ip =~ $valid_ip_pattern ]]; then | |
IFS='.' read -ra octets <<< "$ip" | |
for octet in "${octets[@]}"; do | |
if ((octet < 0 || octet > 255)); then | |
return 1 | |
fi | |
done | |
return 0 | |
else | |
return 1 | |
fi | |
} | |
# Display help documentation | |
display_help() { | |
echo | |
echo "Usage: $0 [IP_ADDRESS [IP_ADDRESS ...] | -f FILE]" | |
echo "Run traceroute against a list of valid IP addresses." | |
echo "Options:" | |
echo " IP_ADDRESS Provide individual IP addresses as arguments" | |
echo " -f FILE Provide a file containing IP addresses (one per line)" | |
echo " -h, --help Display this help message" | |
} | |
# Handle command line arguments | |
while [[ $# -gt 0 ]]; do | |
case "$1" in | |
-h|--help) | |
display_help | |
exit 0 | |
;; | |
-f) | |
shift | |
if [[ -f "$1" ]]; then | |
while IFS= read -r line; do | |
if is_valid_ip "$line"; then | |
run_traceroute "$line" | |
else | |
echo "$line is not a valid IP address." | |
fi | |
done < "$1" | |
else | |
echo "Error: File $1 not found." | |
fi | |
shift | |
;; | |
*) | |
if is_valid_ip "$1"; then | |
run_traceroute "$1" | |
else | |
echo "$1 is not a valid IP address." | |
fi | |
shift | |
;; | |
esac | |
done | |
echo -e "\n-------------------------------------\n" | |
echo "Traceroute completed. Results saved in $output_file." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment