【问题标题】:Getting a remote System timestamp using Jsch Java API使用 Jsch Java API 获取远程系统时间戳
【发布时间】:2018-02-26 16:57:05
【问题描述】:

我正在使用优秀的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 下载一些日志文件。这很好用。

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

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

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

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

【问题讨论】:

  • 您可以尝试在远程服务器上执行date +%m%d%Y%H%M%S(或您需要的任何其他格式)命令并读取输出。检查this question on how execute and read output stackoverflow.com/questions/11532890/…
  • 极好的建议伊万。这似乎做得很好!

标签: java jsch


【解决方案1】:

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

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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    相关资源
    最近更新 更多