获取2台linux机器的时间差

背景

    有些场景下,需要获得2个linux机器的时间差。从网上搜了一些办法如下。

方法

(方法1)clockdiff

参考:https://www.aityp.com/clockdiff/

原理:使用IP报文/ICMP报文头存放的时间戳来比对2个linux机器的时间差。

如果加了参数-o或者-o1,就是用IP报文的时间戳,区别在于-o使用了3个时间戳,-o1使用了4个时间戳。

如果不加参数就是使用ICMP报文的时间戳。

用法:

[ liurong]# clockdiff 10.0.199.24
..
host=10.0.199.24 rtt=562(280)ms/0ms delta=0ms/0ms Tue Apr 21 16:12:48 2020
You have new mail in /var/spool/mail/root

从返回结果中的delta=0ms/0ms,可知,2台机器的时间差为0,可认为是同步的。

得到的结果中

(方法2)linux的date命令

使用date命令打印出当前机器的时间戳,可以精确到ms

命令如下:

[ liurong]# cat time.sh
#/bin/bash
declare startTime=`date +%s%N`;
echo `expr $startTime / 1000000`

执行之后获得本地时间戳

[ liurong]# sh time.sh
1587457576467

查看2台机器的时间戳

[ liurong]# cat get_time.sh
#!/bin/bash

MASTER=10.96.2.194
SLAVE=10.96.2.208

function get_master()
{
declare startTime=`date +%s%N`;
echo `expr $startTime / 1000000`
}


function get_slave()
{
ssh ${SLAVE} << abc
declare startTime=`date +%s%N`;
echo `expr $startTime / 1000000`
exit
abc
}

get_master
get_slave

(方法3)tcpdump抓包,配合wireshark使用