使用 Jsch Java API 获取远程系统时间戳

Getting a remote System timestamp using Jsch Java API

我正在使用优秀的 com.jcraft.jsch API 使用以下代码连接到远程服务器。

    JSch ssh = new JSch();
    JSch.setConfig(FileTransferConstants.STRICT_HOST_KEY_CHECKING, FileTransferConstants.NO);
    session = ssh.getSession(user, host, port);
    session.setPassword(password);
    session.connect();
    channel = session.openChannel(FileTransferConstants.SFTP);
    channel.connect();
    ChannelSftp sftp = (ChannelSftp) channel;

连接后,我会使用 SFTP 下载一些日志文件。这很好用。

检索文件后,我会根据日志条目的时间戳在本地查询它们 - 我正在寻找特定时间内的条目 window。

到目前为止,它没有给我带来任何问题,因为我的本地系统时间戳与远程时间戳非常相似。但最近我的测试开始失败,因为我的本地时间戳与远程服务器上的时间戳之间存在 5 分钟的差异。

所以我的问题是,是否有使用 Jsch 获取远程系统时间的简单方法?如果是这样,我会简单地检索它并在我的测试中使用它而不是我的本地系统时间。那么希望差异问题应该立即消失!

感谢您阅读并考虑我的问题。

如果其他人遇到同样的问题,请添加评论中的工作建议作为答案。

ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand("date +%m%d%Y%H%M%S"); //Date format could be changed to your desired format
channelExec.connect();

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int index = 0;
while ((line = reader.readLine()) != null) {
   System.out.println(++index + " : " + line);
}

channelExec.disconnect();