Created
February 12, 2018 15:22
-
-
Save jabez007/6624c8cfec001a4a6186e7d709bf5597 to your computer and use it in GitHub Desktop.
A rough Bash script from my Linux server class to ping all the IP addresses on our network
This file contains hidden or 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 | |
# Set the internal field separator | |
IFS=$'\n' | |
ping_count=3 | |
ping_deadline=1 | |
# regex pattern for IP addresses | |
grep_ip="[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | |
# Get the interface used for the internet (probably also used for LAN) | |
# does not open any connection out, it just shows the route needed to get to Google's DNS. | |
my_interface=$(ip route get 8.8.8.8 | grep -oP "dev [a-zA-Z0-9]* " | cut -d " " -f 2) | |
# Get the IP address assigned to that interface | |
ip_netmask=$(ip addr show "$my_interface" | grep -oP "$grep_ip/[0-9]{1,2}") | |
printf "network %s accessible on %s\n" "$ip_netmask" "$my_interface" | |
network_bits=$(echo "$ip_netmask" | cut -d "/" -f 2) | |
# # # # | |
if [ $network_bits -eq 8 ] | |
then | |
network_address=$(echo "$ip_netmask" | cut -d "." -f 1) | |
fi | |
if [ $network_bits -eq 12 ] | |
then | |
network_address=$(echo "$ip_netmask" | cut -d "." -f 1-2) | |
fi | |
if [ $network_bits -eq 24 ] | |
then | |
network_address=$(echo "$ip_netmask" | cut -d "." -f 1-3) | |
fi | |
printf "%s\n\n" "$network_address" | |
# # # # | |
if [ $network_bits -eq 8 ] | |
then | |
for ip in $network_address.{1..254}.{1..254}.{1..254} | |
do | |
printf "Trying %s " "$ip" | |
ping -q -f -w "$ping_deadline" -c "$ping_count" "$ip" | grep rtt | |
printf "\n" | |
done | |
fi | |
if [ $network_bits -eq 12 ] | |
then | |
for ip in $network_address.{1..254}.{1..254} | |
do | |
printf "Trying %s " "$ip" | |
ping -q -f -w "$ping_deadline" -c "$ping_count" "$ip" | grep rtt | |
printf "\n" | |
done | |
fi | |
if [ $network_bits -eq 24 ] | |
then | |
for ip in $network_address.{1..254} | |
do | |
printf "Trying %s " "$ip" | |
ping -q -f -w "$ping_deadline" -c "$ping_count" "$ip" | grep rtt | |
printf "\n" | |
done | |
fi | |
# # # # | |
unset IFS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment