Java Code Examples for com.jcraft.jsch.Channel#isClosed()

The following examples show how to use com.jcraft.jsch.Channel#isClosed() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
private void testClose(TestContext context, Consumer<Term> closer) throws Exception {
  Async async = context.async();
  termHandler = term -> {
    term.closeHandler(v -> {
      async.complete();
    });
    closer.accept(term);
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  while (channel.isClosed()) {
    Thread.sleep(10);
  }
}
 
Example 2
Source File: CommandDelegatorMethods.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static String logJsch(Channel channel, InputStream in) 
{
	StringBuilder builder = new StringBuilder();
    try {
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                builder.append((new String(tmp, 0, i)));
            }
            if (channel.isClosed()) {
            //	LOGGER.debug("exit-status: " + channel.getExitStatus());
                break;
            }
        }
    } catch (Exception ex) {
    	LOGGER.error(ex);
    }
    return builder.toString();
}
 
Example 3
Source File: CommandAsObjectResponserMethods.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void logJsch(Channel channel, InputStream in) 
	{
	    try {
	        byte[] tmp = new byte[1024];
	        while (true) {
/*	            while (in.available() > 0) {
	                int i = in.read(tmp, 0, 1024);
	                if (i < 0)
	                    break;
	                LOGGER.debug(new String(tmp, 0, i));
	            }
*/	            if (channel.isClosed()) {
	            	LOGGER.debug("exit-status: " + channel.getExitStatus());
	                break;
	            }
	        }
	    } catch (Exception ex) {
	    	LOGGER.error(ex);
	    }
	}
 
Example 4
Source File: JschExecutor.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static String logJsch(Channel channel, InputStream in) 
{
	StringBuilder builder = new StringBuilder();
    try {
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                builder.append((new String(tmp, 0, i)));
            }
            if (channel.isClosed()) {
            //	LOGGER.debug("exit-status: " + channel.getExitStatus());
                break;
            }
        }
    } catch (Exception ex) {
    	LOGGER.error(ex);
    }
    return builder.toString();
}
 
Example 5
Source File: CommandExecutorHA.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static String logJsch(Channel channel, InputStream in) 
{
	StringBuilder builder = new StringBuilder();
    try {
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                builder.append((new String(tmp, 0, i)));
            }
            if (channel.isClosed()) {
            //	LOGGER.debug("exit-status: " + channel.getExitStatus());
                break;
            }
        }
    } catch (Exception ex) {
    	LOGGER.error(ex);
    }
    return builder.toString();
}
 
Example 6
Source File: SessionEstablisher.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method validates the executed command
 * 
 * @param channel
 *            SSH channel
 * @param in
 *            input stream
 * @return Error message if any

 *             If any error occurred
 */
private static String validateCommandExecution(Channel channel, InputStream in) throws IOException, InterruptedException {
	StringBuilder sb = new StringBuilder();
	byte[] tmp = new byte[Constants.ONE_ZERO_TWO_FOUR];
	while (true) {
		while (in.available() > 0) {
			int i = in.read(tmp, 0,Constants.ONE_ZERO_TWO_FOUR);
			if (i < 0){
				break;
			}
			sb.append(new String(tmp, 0, i));
		}
		if (channel.isClosed()) {
			break;
		}
		Thread.sleep(Constants.THOUSAND);
	}
	return sb.toString();
}
 
Example 7
Source File: SshConnectionImpl.java    From gerrit-events with MIT License 6 votes vote down vote up
/**
 * Blocks until the given channel is close or the timout is reached
 *
 * @param channel the channel to wait for
 * @param timoutInMs the timeout
 */
private static void waitForChannelClosure(Channel channel, long timoutInMs) {
    final long start = System.currentTimeMillis();
    final long until = start + timoutInMs;
    try {
        while (!channel.isClosed() && System.currentTimeMillis() < until) {
            Thread.sleep(CLOSURE_WAIT_INTERVAL);
        }
        logger.trace("Time waited for channel closure: " + (System.currentTimeMillis() - start));
    } catch (InterruptedException e) {
        logger.trace("Interrupted", e);
    }
    if (!channel.isClosed()) {
        logger.trace("Channel not closed in timely manner!");
    }
}
 
Example 8
Source File: AbstractCommandHandler.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected JschResponse getStringFromStream(Channel channel) throws IOException,
		JSchException {
	JschResponse jschResponse = new JschResponse();
	StringBuilder response = new StringBuilder();		
	InputStream in = channel.getInputStream();
	channel.connect();
	jschResponse.setChannelId(channel.getId());
	byte[] tmp = new byte[1024];
	while (true) {
		while (in.available() > 0) {
			int i = in.read(tmp, 0, 1024);
			if (i < 0)
				break;
			response.append(new String(tmp, 0, i));
		}
		if (channel.isClosed()) {
			if (in.available() > 0)
				continue;
			jschResponse.setChannelExitStatus(channel.getExitStatus());
			break;
		}
		try {
		} catch (Exception ee) {
			LOGGER.error("Exception occured while reading stream from Channel #Id["+jschResponse.getChannelId()+"]", ee);
		}
	}
	jschResponse.setResponse(response.toString());
	return jschResponse;
}
 
Example 9
Source File: JschUtil.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets the channel.
 * 
 * @param session
 *            the session
 * @param command
 *            the command
 * @return the channel
 * @throws JSchException
 *             the j sch exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Channel getChannel(Session session, String command) throws JSchException, IOException {
	session.connect();
	Channel channel = session.openChannel("exec");

	((ChannelExec) channel).setCommand(command);
	channel.setInputStream(null);

	InputStream in = channel.getInputStream();

	channel.connect();
	((ChannelExec) channel).setErrStream(System.err);

	byte[] tmp = new byte[RemotingConstants.ONE_ZERO_TWO_FOUR];
	while (true) {
		while (in.available() > 0) {
			int i = in.read(tmp, 0, RemotingConstants.ONE_ZERO_TWO_FOUR);
			if (i < 0){
				break;
			}
		}
		if (channel.isClosed()) {
			break;
		}
	}
	return channel;
}
 
Example 10
Source File: SshUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Launch a command on the remote host and exit once the command is done.
 * 
 * @param session the session to use.
 * @param command the command to launch.
 * @return the output of the command.
 * @throws JSchException
 * @throws IOException
 */
private static String launchACommand( Session session, String command ) throws JSchException, IOException {
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);
    InputStream in = channel.getInputStream();
    channel.connect();
    StringBuilder sb = new StringBuilder();
    byte[] tmp = new byte[1024];
    while( true ) {
        while( in.available() > 0 ) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            sb.append(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
            if (in.available() > 0)
                continue;
            System.out.println("exitstatus: " + channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
    }
    channel.disconnect();
    String remoteResponseStr = sb.toString().trim();
    return remoteResponseStr;
}
 
Example 11
Source File: SshUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Launch a command on the remote host and exit even if the command is not done (useful for launching daemons).
 * 
 * @param session the session to use.
 * @param command the command to launch.
 * @return the output of the command.
 * @throws JSchException
 * @throws IOException
 */
private static String launchACommandAndExit( Session session, String command ) throws JSchException, IOException {
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);
    InputStream in = channel.getInputStream();
    channel.connect();
    StringBuilder sb = new StringBuilder();
    byte[] tmp = new byte[1024];
    while( true ) {
        while( in.available() > 0 ) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            sb.append(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
            if (in.available() > 0)
                continue;
            break;
        }
        try {
            if (sb.length() > 0) {
                break;
            }
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
    }
    channel.disconnect();
    String remoteResponseStr = sb.toString().trim();
    return remoteResponseStr;
}
 
Example 12
Source File: SshProcessContainer.java    From reef with Apache License 2.0 5 votes vote down vote up
private String getRemoteHomePath() {
  final String getHomeCommand = "pwd";
  try {
    final Channel channel = this.remoteSession.openChannel("exec");
    ((ChannelExec) channel).setCommand(getHomeCommand);
    channel.setInputStream(null);
    final InputStream stdout = channel.getInputStream();
    channel.connect();

    byte[] tmp = new byte[1024];
    StringBuilder homePath = new StringBuilder();
    while (true) {
      while (stdout.available() > 0) {
        final int len = stdout.read(tmp, 0, 1024);
        if (len < 0) {
          break;
        }
        homePath = homePath.append(new String(tmp, 0, len, StandardCharsets.UTF_8));
      }
      if (channel.isClosed()) {
        if (stdout.available() > 0) {
          continue;
        }
        break;
      }
    }
    return homePath.toString().trim();
  } catch (final JSchException | IOException ex) {
    throw new RuntimeException("Unable to retrieve home directory from " +
        this.remoteHostName + " with the pwd command", ex);
  }
}
 
Example 13
Source File: JavaConnect.java    From ssh-shell-spring-boot with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

        String host = "localhost";
        String user = "user";
        int port = 2222;
        String password = "password";
        String command = "help";

        try {

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig(config);
            session.connect();
            System.out.println("Connected");

            Channel channel = session.openChannel("shell");
            channel.connect();

            channel.getOutputStream().write((command + "\r").getBytes(StandardCharsets.UTF_8));
            channel.getOutputStream().flush();
            channel.setInputStream(null);

            InputStream in = channel.getInputStream();

            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(3000);
                } catch (Exception ee) {
                }
            }
            channel.disconnect();
            session.disconnect();
            System.out.println("DONE");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example 14
Source File: SSHCommandExecutor.java    From journaldev with MIT License 4 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
    String host="test.journaldev.com";
    String user="my_user";
    String password="my_pwd";
    String command1="cd Apps;ls -ltr";
    try{
    	
    	java.util.Properties config = new java.util.Properties(); 
    	config.put("StrictHostKeyChecking", "no");
    	JSch jsch = new JSch();
    	Session session=jsch.getSession(user, host, 22);
    	session.setPassword(password);
    	session.setConfig(config);
    	session.connect();
    	System.out.println("Connected");
    	
    	Channel channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command1);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);
        
        InputStream in=channel.getInputStream();
        channel.connect();
        byte[] tmp=new byte[1024];
        while(true){
          while(in.available()>0){
            int i=in.read(tmp, 0, 1024);
            if(i<0)break;
            System.out.print(new String(tmp, 0, i));
          }
          if(channel.isClosed()){
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
          }
          try{Thread.sleep(1000);}catch(Exception ee){}
        }
        channel.disconnect();
        session.disconnect();
        System.out.println("DONE");
    }catch(Exception e){
    	e.printStackTrace();
    }

}
 
Example 15
Source File: AbstractSshExecOperation.java    From fraud-detection-tutorial with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(Session session, EventListener listener) {
  try {
    System.out.println("1");
    Channel channel = session.openChannel("exec");
    System.out.println("2");
    InputStream in = channel.getInputStream();
    System.out.println("3");

    //((ChannelExec)channel).setCommand("df");
    //((ChannelExec)channel).setCommand("top -n 1 -b");
    //((ChannelExec)channel).setCommand("ifconfig");
    //((ChannelExec)channel).setCommand("netstat -s");
    ((ChannelExec) channel).setCommand(getCommand());

    System.out.println("4");
    channel.connect();
    System.out.println("5");

    StringBuffer strBuffer = new StringBuffer();

    byte[] tmp = new byte[1024];
    while (true) {
      while (in.available() > 0) {
        int i = in.read(tmp, 0, 1024);
        if (i < 0) break;
        strBuffer.append(new String(tmp, 0, i));
      }
      if (channel.isClosed()) {
        if (in.available() > 0) continue;
        System.out.println("exit-status: " + channel.getExitStatus());
        break;
      }
      try {
        Thread.sleep(1000);
      } catch (Exception ee) {
      }
    }

    System.out.println("6");
    //channel.disconnect();

    String results = strBuffer.toString();


    processResults(session.getHost(), session.getPort(), results, listener);

  } catch (Exception e ){
    e.printStackTrace();
  }
}