欢迎访问生活随笔!

生活随笔

您现在的位置是:首页 > 形式科学 > 操作系统 > Linux

Linux

如何在Linux/Unix之上绑定ntpd到特定的IP地址

发布时间:2022-06-09Linux 系统管理员
NTP 是网络时间协议的首字母简写,这是一个用来同步两台电脑之间时间的协议。ntpd 是一个操作系统守护进程,可以设置并且保证系统的时间与互联网标准时间服务器同步。

默认的情况下,我们的 ntpd/NTP 服务器会监听所有的端口或者 IP 地址,也就是:0.0.0.0:123。 怎么才可以在一个 Linux 或是 FreeBSD Unix 服务器上,确保只监听特定的 IP 地址,比如 localhost 或者是 192.168.1.1:123

NTP 是网络时间协议Network Time Protocol的首字母简写,这是一个用来同步两台电脑之间时间的协议。ntpd 是一个操作系统守护进程,可以设置并且保证系统的时间与互联网标准时间服务器同步。

NTP 使用 /etc/directory 之下的 ntp.conf 作为配置文件。

 

/etc/ntp.conf 之中的端口指令

你可以通过设置端口命令来防止 ntpd 监听 0.0.0.0:123,语法如下:

  1. interface listen IPv4|IPv6|all
  2. interface ignore IPv4|IPv6|all
  3. interface drop IPv4|IPv6|all

上面的配置可以使 ntpd 监听那个地址或者不出来任何请求而直接丢弃。ignore 会防止打开匹配的地址,drop 会导致 ntpd 打开该地址并丢弃所有接收到的包,而不做任何检查。举个例子,如果要忽略所有端口之上的监听,加入下面的语句到 /etc/ntp.conf

  1. interface ignore wildcard

如果只监听 127.0.0.1 和 192.168.1.1 则是这样:

  1. interface listen 127.0.0.1
  2. interface listen 192.168.1.1

这是我 FreeBSD 云服务器上的样例 /etc/ntp.conf 文件:

  1. $ egrep -v '^#|$^' /etc/ntp.conf

样例输出为:

  1. tos minclock 3 maxclock 6
  2. pool 0.freebsd.pool.ntp.org iburst
  3. restrict default limited kod nomodify notrap noquery nopeer
  4. restrict -6 default limited kod nomodify notrap noquery nopeer
  5. restrict source limited kod nomodify notrap noquery
  6. restrict 127.0.0.1
  7. restrict -6 ::1
  8. leapfile "/var/db/ntpd.leap-seconds.list"
  9. interface ignore wildcard
  10. interface listen 172.16.3.1
  11. interface listen 10.105.28.1

 

重启 ntpd

在 FreeBSD Unix 之上重新加载/重启 ntpd:

  1. $ sudo /etc/rc.d/ntpd restart

或者 在 Debian 和 Ubuntu Linux 之上使用下面的命令:

  1. $ sudo systemctl restart ntp

或者 在 CentOS/RHEL 7/Fedora Linux 之上使用下面的命令:

  1. $ sudo systemctl restart ntpd

 

校验

使用 netstatss 命令来检查 ntpd 只绑定到了特定的 IP 地址:

  1. $ netstat -tulpn | grep :123

或是:

  1. $ ss -tulpn | grep :123

样例输出:

  1. udp 0 0 10.105.28.1:123 0.0.0.0:* -
  2. udp 0 0 172.16.3.1:123 0.0.0.0:* -

在 FreeBSD Unix 服务器上使用 sockstat 命令:

  1. $ sudo sockstat
  2. $ sudo sockstat -4
  3. $ sudo sockstat -4 | grep :123

样例输出:

  1. root ntpd 59914 22 udp4 127.0.0.1:123 *:*
  2. root ntpd 59914 24 udp4 127.0.1.1:123 *:*