借用nc自动同步时间

当系统中没有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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值