0

I am using the excellent com.jcraft.jsch API to connect to a remote server using the following code.

    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;

Once connected, I then use SFTP to download some log files. This works very well.

Once the files have been retrieved, I interrogate them locally based on the timestamps of the log entries - I am looking for entries within a specific time window.

Up until now it has caused me no problem because my local system timestamp has been very similar to the remote timestamp. But recently my tests started failing due to there now being a 5 minute discrepancy between my local timestamp and that on the remote server.

So my question is, is there is a simple way of getting the remote system time using Jsch? If so, I would simply retrieve this and use it in my tests instead of my local system time. Then hopefully the discrepancy issue should immediately go away!

Thank you for reading and considering my question.

2
  • You could try to execute date +%m%d%Y%H%M%S (or ay other format you need) command on the remote server and read output. Check this question on how execute and read output stackoverflow.com/questions/11532890/… Commented Feb 26, 2018 at 17:05
  • Excellent suggestion Ivan. This seems to do the job just great! Commented Feb 27, 2018 at 11:07

1 Answer 1

2

Adding working suggestion from comment as an answer if anybody else faces the same problem.

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.