I am running a Java application on an remote server by making a connection with remote server through java secure channel. My application executes a shell script on an remote server and get's the result from that. Then again my application makes connection with another remote server then gets result from that. But if sometimes the commands are not executing on first remote server then my java application goes on waiting. So my question is how to tell my java application not to wait after certain time and make connection with another remote server. Help will be appreciated.

I am executing the below command and trying to get result from remote server

echo stat | nc hostname.com 2181

If in case command nc has been uninstalled from remote server my application is waiting more than I expected. So how to solve this

I mean after certain time it has to close the connection with remote server and start connecting with other remote server and try execute shell scripts on that server.

The below code I am using to connect to remote server

   JSch jsch = new JSch();
    Session session = null;
    Channel channel = null;
    StringBuilder log = new StringBuilder();

    String response = null;
    String response1 = null;

    try {
        session = jsch.getSession(username, host, port);
        session.setConfig(HOST_KEY_CHECKING, hostKey);
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        // check if connect was successful
        if (session.isConnected()) {
            System.out.println("Connected sucessfully to server :" + host);

            channel = session.openChannel(EXCUTE_CHANNEL);

            ((ChannelExec) channel).setCommand(command10);
            // channel.setInputStream(System.in);
            ((ChannelExec) channel).setErrStream(System.err);
            InputStream in = channel.getInputStream();
            response = IOUtils.toString(in);

        } else {
            System.out.println("Connection Failed" + host);
    } catch (JSchException e) {
        System.out.println("Connection Failed" + host + " Error:" + e.getMessage());
    } catch (Exception e) {
        System.out.println("Connection Failed" + host + " Error:" + e.getMessage());

    System.out.println( "First Response received :"+  response);
    return response;

You may use the timeout command.

timeout 10s echo stat | nc hostname.com 2181

This waits for 10 seconds and then moves on with the proceedings.

  • It is not working. I tried with wrong command as timeout 10s echo stat | nc worng_hostname.com 2181. Then it stopped there only it's not moving further. Do anyone have another solution for this? – Manikya Sep 2 '16 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.