-1

I was wondering if there is a way to write to /etc/hosts file an entry by doing the following using a bash script (.sh)

  1. Get the ip of a host command for e.g. (could be any URL)

host cloud.com

  1. The reslt would be as follows:

cloud.com has address 50.17.245.212

  1. Finally, I want to insert into the /etc/hosts file the following:

50.17.245.212 ip-50-17-245-212

Note: First IP is of the URL and then followed by that it is prefixed with -ip and then dots are replaced with "-"

I tried with dig but the result is long, would appreciate any pointers here.

Saffik
  • 911
  • 4
  • 19
  • 45
  • ... and why would you even want this? So you have an URL, you check if the website exists, and in case it does, instead of adding it to the /etc/hosts file (like the entry "cloud.com 50.17.245.212" you invent another hostname, purely based on the IP, and add this to the /etc/hosts file without reference to the original URL? – Dominique Jul 13 '20 at 15:58
  • 1
    Does this answer your question? [Ip host script bash](https://stackoverflow.com/questions/62182898/ip-host-script-bash) – alecxs Jul 13 '20 at 16:00
  • @alecxs - not quite – Saffik Jul 13 '20 at 16:02
  • @Dominique - It is for an experiment. I know what you're saying but need to do it. – Saffik Jul 13 '20 at 16:03
  • *ip=$(host cloud.com | cut -d ' ' -f4); echo "$ip ip-${ip//+([.:])/-}" >> /etc/hosts* or use [regex](https://stackoverflow.com/a/37355379) for catching valid ipv4/ipv6 address instead of *cut* – alecxs Jul 13 '20 at 16:20
  • @alecxs - do you want to post your response as a proper answer, i will accept it. – Saffik Jul 13 '20 at 16:27
  • 1
    The proper way to use dig is with +short (`dig +short cloud.com`) but alexcs' oneliner works regardless. – micke Jul 13 '20 at 16:46

2 Answers2

3

A single (GNU) sed command:

host cloud.com |
sed -E -n 's/.* has address (([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)).*/\1 ip-\2-\3-\4-\5/p'

Redirect the output as needed such as >> /etc/hosts

M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
2
url=cloud.com

whitespace as delimiter for cut to print only 4th field

ip=$(host $url | cut -d ' ' -f4)

or regex for grep only valid ipv4/ipv6

ip=$(host $url | grep -ioE '([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) | (([a-f0-9:]+:+)+[a-f0-9]+)')

echo variable ${ip} with string manipulation // replace +() multiple occurences of [.:] dots or colons / with -

echo "$ip ip-${ip//+([.:])/-}" | tee -a /etc/hosts
RobC
  • 22,977
  • 20
  • 73
  • 80
alecxs
  • 701
  • 8
  • 17