当系统中没有ntp时,我们可以借助 nc 工具实现自动同步系统时间。当然,至少由一台机器的时间是准确的。原理比较简单,借助 nc 构建 server 和 client,然后在 server 端通过文件传输时间信息,在 client 端通过文件接收时间信息,最后设置系统时间。代码如下所示:
server 端,./nc_server.sh:
#!/bin/sh
tmp_file=./time.txt
touch $tmp_file
while true
do
date +"%Y-%m-%d %H:%M:%S" > $tmp_file
nc -l 1234 < $tmp_file
cat $tmp_file
done
client 端,./nc_client.sh:
#!/bin/sh
tmp_file=./time.txt
touch $tmp_file
nc -W 1 10.20.42.87 1234 > $tmp_file
sleep 0.1
nc -W 1 10.20.42.87 1234 > $tmp_file
read _time < $tmp_file
echo "The time read from the server is: $_time"
date -s "$_time"
client 请求 server 两次的原因是 server 中的 nc 会阻塞,第一次读到的时间大概率不是最新的,而第二次读到的时间才基本上是最新的。
运行效果:
server 端:
$ ./nc_server.sh
2020-12-23 16:20:38
2020-12-23 16:20:40
client 端:
$ ./nc_client.sh
The time read from the server is: 2020-12-23 16:20:40
2020年 12月 23日 星期三 16:20:40 CST