For scanning my subnet using my IP address, I need to run the following command
nmap -sn 192.168.100.*
I want to extend this functionality such that I don't have to manually specify the first three parts of the IP range myself. I came up with this rough solution.
ip=$( hostname -I | awk '{print 1ドル}' | awk -F. '{print 1ドル; print 2ドル; print 3ドル}' ORS="."; echo -n "*");
nmap -sn $ip
Is there a more cleaner way of achieving the same?
2 Answers 2
This is pretty reasonable. I'd have awk
do a bit more of the work:
ip=$( hostname -I | awk '{print 1ドル}' | awk -F. '{OFS="."; print 1,ドル 2,ドル 3,ドル"*"}'; );
I switched from ORS
(output record separator) to OFS
(output field separator) to use print
in awk
with commas. The commas tell it that we have multiple fields which gets rid of two "extra" print
statements. This also let me move the literal *
inside of awk
which eliminates the shell echo
. So I feel this is more succinct without being harder to follow.
It might be nice to combine the awk
s into one, but it is pretty clear what each one does and it isn't like you're processing reams of data here.
-
2\$\begingroup\$ You could drop
awk '{print 1ドル}'
in the middle and expect the same output ;-) \$\endgroup\$janos– janos2018年11月30日 17:22:22 +00:00Commented Nov 30, 2018 at 17:22
You can do it purely in Bash, using ${parameter%word}
to strip off the last octet from the IP address.
hostname -I | while read ip _ ; do
nmap -sn ${ip%.*}.\*
done
Note that hostname -I
is not portable: the -I
option appears to be a GNU extension.
-
3\$\begingroup\$ Although it's reasonable to expect that
hostname -I
will not output something malicious, as a rule of thumb it's always good to double-quote variables used in command arguments, and written like this might be slightly kinder on the eyes too:nmap -sn "${ip%.*}.*"
\$\endgroup\$janos– janos2018年11月30日 17:27:47 +00:00Commented Nov 30, 2018 at 17:27