简体   繁体   中英

test if hostname exists from command line without ping

we have a script that needs to take action on a finite list of hosts. but every time we add or remove a host to the /etc/hosts file, we end up having to update this script.

basically, say my hosts file looks like:

192.168.100.1     hostip_1
192.168.100.2     hostip_2
192.168.100.10    hostip_3
192.168.100.20    hostip_5

and my script (bash) does something like:

callmyfunction hostip_1
callmyfunction hostip_2
callmyfunction hostip_3
callmyfunction hostip_5

if i want to add hostip_4 to the list of hosts, i now have to go in and edit my script and add it to the list. while it's a small edit, it is still a step that can be forgotten in the process (especially if someone new to the system comes in).

is there a way i can test to see if 'hostip_1' is a valid hostname within the system (without pinging the host or grepping the /etc/hosts file)? we may use multiple hosts files, and different configurations may have different filenames, so i can't rely on trying to grep a single file. i need the system to do that work for me.

any clues?

first, my statement about things not being in the hosts file is wrong. that is exactly where they are. dumb on my part.

but the answer is:

getent hosts

that will get it to print everything out, and i can do a lookup from there.

might not be in your /etc/hosts file... better search for the name and see if an ip can be found:

(($(dig +noall +answer google.de |wc -c)>0)) && echo exists

this is bash, can be adaptet to pretty much everything.

dig +noall +answer google.de

returns the ips if found. If empty, that name cannot be used in the computer running this code.

As you are populating the /etc/hosts file, I am assuming that you are not using DNS. So below solution wont fit your use case. But it will still get you some pointers.

In a working DNS environment, you can check the host name to its corresponding IP with below command

# host host_name

This is will give the IP address of the host. In case the host name does not exists, then it will give you corresponding host not found message.

You can parse the output of above command and can deduce whether a give host name exists.

If all the targets are on the same subnet (same network), use arping , it will check that hosts are available using ARP .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM