So if I wanted to connect via SSH to all the devices on a network, using the ARP table to know exactly where to connect, what could I do?
The code would be something like this:
#!/bin/bash
for a in $([ARP Table here?])
do
ssh user@$a true
echo "Connected to $a"
done
I'm not sure on how to store the dinamic IPs in the a variable. Also I'm not sure on the fact that I can use that a variable afterward to connect via ssh, because an IP wouldn't be a int, but more probably a string.
EDIT: After Andrew made me notice that not every device on my network could be in my ARP table, I'm wondering:
Is it better to start from 0 to the maximum value of the current network mask or searching in the ARP table?
Here are the two cases:
#!/bin/bash
for a in $(seq 255)
do
ssh user@172.18.10.$a true
echo "Connected to 172.18.10.$a"
done
or
#!/bin/bash
for a in $([ARP Table here?])
do
ssh user@$a true
echo "Connected to $a"
done
A better solution than developing your own scanning tools might be to use something that already exists.
To see what IP addresses are reachable (which as a side effect will populate your ARP cache), you might use fping
. It's probably available for your OS or distro. An example from my local network:
$ fping -g 10.1.1.0/29
10.1.1.1 is alive
10.1.1.2 is alive
10.1.1.5 is alive
10.1.1.3 is unreachable
10.1.1.4 is unreachable
10.1.1.6 is unreachable
The fping
command is ICMP-only -- it sends pings. If your goal is not just to determine what devices exist, but also whether they are answering on the SSH port (22), you could use tcping
or something equivalent.
for ip in $(seq -f "10.1.1.%g" 1 9); do
if tcping -u 200 -q $ip 22; then
echo "yes: $ip"
fi
done
Another option which might be a little trickier to script would be to use an actual scanning tool, like nmap
(as seen in The Matrix).
If you're using a network monitoring system, check to see if it has network scanning tools built in. Cacti, for example, has a discovery plugin. Nagios has quite a few of them.