Linux

ping Linux 伺服器時如何更改“ping from”值?

  • July 16, 2018

我的伺服器中主機名文件的內容是:

# cat /etc/hostname
sub.mysite.com

但是當我ping的 CentOS 7 伺服器顯示:

# ping sub.mysite.com
64 bytes from sub ...

甚至:

# ping ns1.mysite.com
   64 bytes from sub ...

ping 時如何告訴我的伺服器具有以下輸出?

64 bytes from sub.mysite.com ...

更新

例如在我的客戶上:

user@host:~$ ping ns1.mysite.com
PING ns1.mysite.com (x.x.x.x) 56(84) bytes of data.
64 bytes from sub (x.x.x.x): icmp_seq=1 ttl=56 time=7.88 ms
64 bytes from sub (x.x.x.x): icmp_seq=2 ttl=56 time=5.86 ms
64 bytes from sub (x.x.x.x): icmp_seq=3 ttl=56 time=4.99 ms
64 bytes from sub (x.x.x.x): icmp_seq=4 ttl=56 time=4.88 ms

我想要完整的主機名 (sub.mysite.com) 而不是sub.

ping/etc/hostname用於解析 IP 到名稱的映射,它使用名稱服務 ( netns) 進行這些轉換。順便說一句,/etc/hostname是 systemd 的一部分:

$ rpm -qf /etc/hostname
systemd-219-42.el7_4.10.x86_64

您看到的那個短名稱sub, 來自您/etc/hosts通過名稱服務的文件。如果您使用strace,您可以看到如何ping找到sub

$ strace -s 2000 ping -c1 www.google.com |& grep /etc/host
open("/etc/host.conf", O_RDONLY|O_CLOEXEC) = 4
open("/etc/hosts", O_RDONLY|O_CLOEXEC)  = 4
open("/etc/hosts", O_RDONLY|O_CLOEXEC)  = 4

因此,解決您的問題的簡單方法是將您的伺服器名稱放在您想要在文件ping中顯示的名稱。/etc/hosts

例子

$ ping -c1 www.google.com
PING www.google.com (74.125.141.99) 56(84) bytes of data.
64 bytes from vl-in-f99.1e100.net (74.125.141.99): icmp_seq=1 ttl=63 time=109 ms

--- www.google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 109.903/109.903/109.903/0.000 ms
Now if we were to add that IP, 74.125.141.103, to your `/etc/hosts` file we could manipulate `ping` into showing whatever we want for it:

將此添加到/etc/hosts

74.125.141.99  blah.blah.com

現在重複我們的測試:

$ ping -c1 www.google.com
PING www.google.com (74.125.141.99) 56(84) bytes of data.
64 bytes from blah.blah.com (74.125.141.99): icmp_seq=1 ttl=63 time=109 ms

--- www.google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 109.886/109.886/109.886/0.000 ms

/etc/hosts 的順序

請記住,添加主機的順序/etc/hosts可能會導致名稱顯示為您所看到的。

例如,如果我們在我們的/etc/hosts:

74.125.141.99  blah blah.blah.com

如您所見,將ping顯示一個短名稱:

$ ping -c1 www.google.com
PING www.google.com (74.125.141.99) 56(84) bytes of data.
64 bytes from blah (74.125.141.99): icmp_seq=1 ttl=63 time=108 ms

--- www.google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 108.065/108.065/108.065/0.000 ms

參考

引用自:https://unix.stackexchange.com/questions/456381