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

The following examples show how to use com.jcraft.jsch.Channel#setInputStream() . 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: AbstractSshSupport.java    From sshd-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
void sshCall(String username, String password, SshExecutor executor, String channelType) {
    try {
        Session session = openSession(username, password);
        Channel channel = session.openChannel(channelType);
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream();
        channel.setInputStream(new PipedInputStream(pos));
        channel.setOutputStream(new PipedOutputStream(pis));
        channel.connect();
        try {
            executor.execute(pis, pos);
        } finally {
            pis.close();
            pos.close();
            channel.disconnect();
            session.disconnect();
        }
    } catch (JSchException | IOException ex) {
        fail(ex.toString());
    }
}
 
Example 2
Source File: SessionEstablisher.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method execute the given command over SSH
 * 
 * @param session
 * @param command
 *            Command to be executed
 * @throws JSchException
 * @throws IOException
 * @throws InterruptedException
 */
static String executeCommand(Session session, String command) throws JSchException, IOException {
	InputStream in = null;
	Channel channel = null;
	String msg = null;
	try {
		channel = session.openChannel("exec");
		((ChannelExec) channel).setCommand(command);
		channel.setInputStream(null);
		((ChannelExec) channel).setErrStream(System.err);
		in = channel.getInputStream();
		channel.connect();
		msg = validateCommandExecution(channel, in);
	} catch (InterruptedException e) {
		CONSOLE_LOGGER.error(e);
	} finally {
		if (in != null) {
			in.close();
		}
		if (channel != null) {
			channel.disconnect();
		}
	}
	return msg;
}
 
Example 3
Source File: SshHelperTest.java    From ssh-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
public static void call(String user, String pass, String host, int port, Executor executor) {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setPassword(pass);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        Channel channel = session.openChannel("shell");
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream();
        channel.setInputStream(new PipedInputStream(pos));
        channel.setOutputStream(new PipedOutputStream(pis));
        channel.connect();
        try {
            executor.execute(pis, pos);
        } catch (Exception e) {
            fail(e.toString());
        } finally {
            pis.close();
            pos.close();
            channel.disconnect();
            session.disconnect();
        }
    } catch (JSchException | IOException ex) {
        fail(ex.toString());
    }
}
 
Example 4
Source File: TelemetryTools.java    From anx with Apache License 2.0 5 votes vote down vote up
List<String> execSSHCommand(String command) throws JSchException, IOException {
    JSch jSch = new JSch();

    Window loadingWindow = showLoadingWindow("SSH exec: " + command);

    Session session = jSch.getSession(view.username, view.host, 22);
    session.setDaemonThread(true);
    session.setTimeout(3600000);
    session.setServerAliveInterval(15000);
    session.setConfig("StrictHostKeyChecking", "no");
    session.setPassword(view.password);
    try {
        session.connect();

        Channel channel = session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
        channel.setInputStream(null);
        InputStream input = channel.getInputStream();
        channel.connect();
        List<String> result = new BufferedReader(new InputStreamReader(input)).lines().collect(Collectors.toList());

        channel.disconnect();
        session.disconnect();
        return result;
    } finally {
        loadingWindow.close();
    }
}
 
Example 5
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 6
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 7
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 8
Source File: MyConnectionHandler.java    From XMouse with MIT License 5 votes vote down vote up
protected String doInBackground(String... params) {
    StringBuilder log = new StringBuilder();

    try {

        Channel channel = session.openChannel("exec");
        ((ChannelExec)channel).setCommand(cmd);

        // X Forwarding
        //channel.setXForwarding(true);

        //channel.setInputStream(System.in);
        channel.setInputStream(null);
        BufferedReader r = new BufferedReader(new InputStreamReader(((ChannelExec) channel).getErrStream()));
        //InputStream in=channel.getInputStream();
        BufferedReader r2 = new BufferedReader(new InputStreamReader(channel.getInputStream()));
        channel.connect();
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line);
        }
        while ((line = r2.readLine()) != null) {
            total.append(line);
        }
        channel.disconnect();
        //session.disconnect();
        log.append(total.toString());

    } catch (Exception e){
        e.printStackTrace();
        log.append(e.getMessage());
    }
    return log.toString();
}
 
Example 9
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 10
Source File: SshUtil.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a given command. It opens exec channel for the command and closes
 * the channel when it's done.
 *
 * @param session ssh connection to a remote server
 * @param command command to execute
 * @return command output string if the command succeeds, or null
 */
public static String executeCommand(Session session, String command) {
    if (session == null || !session.isConnected()) {
        log.error("Invalid session({})", session);
        return null;
    }

    log.info("executeCommand: ssh command {} to {}", command, session.getHost());

    try {
        Channel channel = session.openChannel("exec");

        if (channel == null) {
            log.debug("Invalid channel of session({}) for command({})", session, command);
            return null;
        }

        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        InputStream output = channel.getInputStream();

        channel.connect();
        String result = CharStreams.toString(new InputStreamReader(output, StandardCharsets.UTF_8));
        log.trace("SSH result(on {}): {}", session.getHost(), result);
        channel.disconnect();

        return result;
    } catch (JSchException | IOException e) {
        log.debug("Failed to execute command {} due to {}", command, e);
        return null;
    }
}
 
Example 11
Source File: SSHShellUtil.java    From mcg-helper with Apache License 2.0 4 votes vote down vote up
public static String execute(String ip, int port, String userName, String password, String secretKey, String shell) throws JSchException, IOException {
		String response = null;
		JSch.setLogger(new ShellLogger());
		JSch jsch = new JSch();
		Session session = jsch.getSession(userName, ip, port);
		UserInfo ui = null;
		if(StringUtils.isEmpty(secretKey)) {
			ui = new SSHUserInfo(password);
		} else {
			ui = new SSHGoogleAuthUserInfo(secretKey, password);
		}
		session.setUserInfo(ui);
		session.connect(6000);

		Channel channel = session.openChannel("shell");
		PipedInputStream pipedInputStream = new PipedInputStream();
		PipedOutputStream pipedOutputStream = new PipedOutputStream();
		pipedOutputStream.connect(pipedInputStream);
		
		Thread thread = new Thread(new MonitorShellUser(channel, shell, pipedOutputStream));
		thread.start();
		
		channel.setInputStream(pipedInputStream);
		
		PipedOutputStream shellPipedOutputStream = new PipedOutputStream();
		PipedInputStream receiveStream = new PipedInputStream(); 
		shellPipedOutputStream.connect(receiveStream);
		
		channel.setOutputStream(shellPipedOutputStream);
		((ChannelShell)channel).setPtyType("vt100", 160, 24, 1000, 480);   // dumb
		//((ChannelShell)channel).setTerminalMode("binary".getBytes(Constants.CHARSET));
	//	((ChannelShell)channel).setEnv("LANG", "zh_CN.UTF-8");
		try {
			channel.connect();
			response = IOUtils.toString(receiveStream, "UTF-8");
		}finally {
//			if(channel.isClosed()) {
				pipedOutputStream.close();
				pipedInputStream.close();
				shellPipedOutputStream.close();
				receiveStream.close();
				channel.disconnect();
				session.disconnect();
			}
//		}
			
		return response;
	}
 
Example 12
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 13
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 14
Source File: ProfilerJMXDump.java    From jumbune with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * <<<<<<< Updated upstream Opens a new channel,sets the command,input and error streams and return it. ======= Opens a new channel,sets the
 * command,input and error streams and return it. >>>>>>> Stashed changes
 * 
 * @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.
 */
private Channel getChannel(Session session, String command) throws JSchException, IOException {

	Channel channel = session.openChannel(EXECUTION_MODE);
	((ChannelExec) channel).setCommand(command);
	channel.setInputStream(null);
	((ChannelExec) channel).setErrStream(System.err);
	channel.connect();
	return channel;
}