3
\$\begingroup\$

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?

chicks
2,8593 gold badges18 silver badges30 bronze badges
asked Nov 29, 2018 at 4:31
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

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 awks into one, but it is pretty clear what each one does and it isn't like you're processing reams of data here.

answered Nov 29, 2018 at 14:32
\$\endgroup\$
1
  • 2
    \$\begingroup\$ You could drop awk '{print 1ドル}' in the middle and expect the same output ;-) \$\endgroup\$ Commented Nov 30, 2018 at 17:22
6
\$\begingroup\$

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.

answered Nov 29, 2018 at 19:18
\$\endgroup\$
1
  • 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\$ Commented Nov 30, 2018 at 17:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.