com.jcraft.jsch.Channel Java Examples

The following examples show how to use com.jcraft.jsch.Channel. 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: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 7 votes vote down vote up
public static void rm(String user, String password, String addr, int port, List<String> fileName) throws JSchException, SftpException, Exception {
	
	if (fileName==null || fileName.size()<1) {
		return;
	}
	Session session = getSession(user, password, addr, port);				
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;		
	try {
		for (String f : fileName) {
			sftpChannel.rm(f);				
			logger.warn("success remove file from " + addr + " :" + fileName);				
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();				
	}		
}
 
Example #2
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseHandler(TestContext context) throws Exception {
  Async async = context.async();
  termHandler = term -> {
    term.closeHandler(v -> {
      async.complete();
    });
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  channel.disconnect();
  session.disconnect();
}
 
Example #3
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 #4
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 #5
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 #6
Source File: SFTPUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
public SFTPUtil(String host, String user, String password, int port) throws Exception{ 
	this.host = host; 
	this.user = user; 
	this.password = password; 
       Channel channel = null; 
       JSch jsch = new JSch(); 
       session = jsch.getSession(this.user, this.host, this.port);   
       if(BasicUtil.isNotEmpty(this.password)){ 
       	session.setPassword(this.password);   
       } 
       Properties sshConfig = new Properties();   
       sshConfig.put("StrictHostKeyChecking", "no");   
       session.setConfig(sshConfig); 
       session.connect();   
       channel = session.openChannel("sftp");   
       channel.connect();   
       client = (ChannelSftp) channel; 
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
Source File: SFTPClient.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public void login( String password ) throws KettleJobException {
  this.password = password;

  s.setPassword( this.getPassword() );
  try {
    java.util.Properties config = new java.util.Properties();
    config.put( "StrictHostKeyChecking", "no" );
    // set compression property
    // zlib, none
    String compress = getCompression();
    if ( compress != null ) {
      config.put( COMPRESSION_S2C, compress );
      config.put( COMPRESSION_C2S, compress );
    }
    s.setConfig( config );
    s.connect();
    Channel channel = s.openChannel( "sftp" );
    channel.connect();
    c = (ChannelSftp) channel;
  } catch ( JSchException e ) {
    throw new KettleJobException( e );
  }
}
 
Example #12
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeymapFromFilesystem() throws Exception {
  URL url = TermServer.class.getResource(SSHTermOptions.DEFAULT_INPUTRC);
  File f = new File(url.toURI());
  termHandler = Term::close;
  startShell(new SSHTermOptions().setIntputrc(f.getAbsolutePath()).setPort(5000).setHost("localhost").setKeyPairOptions(
    new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")).
    setAuthOptions(new JsonObject()
      .put("provider", "shiro")
      .put("type", "PROPERTIES")
      .put("config",
        new JsonObject().put("properties_path", "classpath:test-auth.properties"))));
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
}
 
Example #13
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testDifferentCharset(TestContext context) throws Exception {
  termHandler = term -> {
    term.write("\u20AC");
    term.close();
  };
  startShell(new SSHTermOptions().setDefaultCharset("ISO_8859_1").setPort(5000).setHost("localhost").setKeyPairOptions(
    new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")).
    setAuthOptions(new JsonObject()
      .put("provider", "shiro")
      .put("type", "PROPERTIES")
      .put("config",
        new JsonObject().put("properties_path", "classpath:test-auth.properties"))));
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  InputStream in = channel.getInputStream();
  int b = in.read();
  context.assertEquals(63, b);
}
 
Example #14
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Vector<LsEntry> getRemoteFileList(String user, String password, String addr, int port, String cwd) throws JSchException, 
	SftpException, Exception {
	
	Session session = getSession(user, password, addr, port);	
	Vector<LsEntry> lsVec=null;
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;
	try {
		lsVec=(Vector<LsEntry>)sftpChannel.ls(cwd); //sftpChannel.lpwd()
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();			
	}		
	return lsVec;		
}
 
Example #15
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * 本地檔案放到遠端SFTP上
 * 	
 * @param user
 * @param password
 * @param addr
 * @param port
 * @param localFile
 * @param remoteFile
 * @throws JSchException
 * @throws SftpException
 * @throws Exception
 */
public static void put(String user, String password, String addr, int port,
		List<String> localFile, List<String> remoteFile) throws JSchException, SftpException, Exception {
	
	Session session = getSession(user, password, addr, port);	
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;		
	try {
		for (int i=0; i<localFile.size(); i++) {
			String rf=remoteFile.get(i);
			String lf=localFile.get(i);
			logger.info("put local file: " + lf + " write to " + addr + " :" + rf );
			sftpChannel.put(lf, rf);
			logger.info("success write to " + addr + " :" + rf);
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();				
	}		
}
 
Example #16
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 #17
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 #18
Source File: JavaStatusChecker.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Stops java application that needs to, this should be called when the user wants to manually stop the application
 * so that it kills the remote java process
 *
 * @param session
 * @param isRunningAsRoot
 * @param mainClass
 * @throws JSchException
 * @throws IOException
 */
public void forceStopJavaApplication(@Nullable Session session, @NotNull boolean isRunningAsRoot, @NotNull String mainClass) throws JSchException, IOException {
    if (session == null) {
        return;
    }
    String javaKillCmd = String.format("%s kill -9 $(ps -efww | grep \"%s\"| grep -v grep | tr -s \" \"| cut -d\" \" -f2)",
            isRunningAsRoot ? "sudo" : "", mainClass);
    Channel channel = session.openChannel("shell");

    OutputStream inputstream_for_the_channel = channel.getOutputStream();
    PrintStream commander = new PrintStream(inputstream_for_the_channel, true);

    channel.connect();

    commander.println(javaKillCmd);
    commander.close();
    channel.disconnect();
    session.disconnect();
}
 
Example #19
Source File: SSHShellTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeployServiceWithShiroAuthOptions(TestContext context) throws Exception {
  Async async = context.async();
  vertx.deployVerticle("service:io.vertx.ext.shell", new DeploymentOptions().setConfig(new JsonObject().put("sshOptions",
      new JsonObject().
          put("host", "localhost").
          put("port", 5000).
          put("keyPairOptions", new JsonObject().
              put("path", "src/test/resources/server-keystore.jks").
              put("password", "wibble")).
          put("authOptions", new JsonObject().put("provider", "shiro").put("config",
              new JsonObject().
                  put("properties_path", "classpath:test-auth.properties")))))
      , context.asyncAssertSuccess(v -> {
    async.complete();
  }));
  async.awaitSuccess(2000);
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  channel.disconnect();
  session.disconnect();
}
 
Example #20
Source File: SshConnectionImpl.java    From gerrit-events with MIT License 6 votes vote down vote up
/**
 * Execute an ssh command on the server, without closing the session
 * so that a Reader can be returned with streaming data from the server.
 *
 * @param command the command to execute.
 * @return a Reader with streaming data from the server.
 * @throws IOException  if it is so.
 * @throws SshException if there are any ssh problems.
 */
@Override
public synchronized Reader executeCommandReader(String command) throws SshException, IOException {
    if (!isConnected()) {
        throw new IllegalStateException("Not connected!");
    }
    try {
        Channel channel = connectSession.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
        InputStreamReader reader = new InputStreamReader(channel.getInputStream(), "utf-8");
        channel.connect();
        return reader;
    } catch (JSchException ex) {
        throw new SshException(ex);
    }
}
 
Example #21
Source File: Ssh.java    From BigDataScript with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to a remote host and return a channel (session and jsch are set)
 */
Channel connect(String channleType, String sshCommand) throws Exception {
	JSch.setConfig("StrictHostKeyChecking", "no"); // Not recommended, but useful
	jsch = new JSch();

	// Some "reasonable" defaults
	if (Gpr.exists(defaultKnownHosts)) jsch.setKnownHosts(defaultKnownHosts);
	for (String identity : defaultKnownIdentity)
		if (Gpr.exists(identity)) jsch.addIdentity(identity);

	// Create session and connect
	if (debug) Gpr.debug("Create conection:\n\tuser: '" + host.getUserName() + "'\n\thost : '" + host.getHostName() + "'\n\tport : " + host.getPort());
	session = jsch.getSession(host.getUserName(), host.getHostName(), host.getPort());
	session.setUserInfo(new SshUserInfo());
	session.connect();

	// Create channel
	channel = session.openChannel(channleType);
	if ((sshCommand != null) && (channel instanceof ChannelExec)) ((ChannelExec) channel).setCommand(sshCommand);

	return channel;
}
 
Example #22
Source File: SshHandler.java    From Jpom with MIT License 5 votes vote down vote up
HandlerItem(WebSocketSession session,
            InputStream inputStream,
            OutputStream outputStream,
            Session openSession,
            Channel channel,
            Charset charset) {
    this.session = session;
    this.inputStream = inputStream;
    this.outputStream = outputStream;
    this.openSession = openSession;
    this.channel = channel;
    this.charset = charset;
}
 
Example #23
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testType(TestContext context) throws Exception {
  Async async = context.async();
  termHandler = term -> {
    context.assertEquals("vt100", term.type());
    async.complete();
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
}
 
Example #24
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 #25
Source File: SshLocalhostNoEchoExample.java    From ExpectIt with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws JSchException, IOException {
    JSch jSch = new JSch();
    Session session = jSch.getSession(System.getenv("USER"), "localhost");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    jSch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa");
    session.setConfig(config);
    session.connect();
    Channel channel = session.openChannel("shell");
    channel.connect();

    Expect expect = new ExpectBuilder()
            .withOutput(channel.getOutputStream())
            .withInputs(channel.getInputStream(), channel.getExtInputStream())
            .build();
    try {
        expect.expect(contains("$"));
        expect.sendLine("stty -echo");
        expect.expect(contains("$"));
        expect.sendLine("pwd");
        System.out.println("pwd1:" + expect.expect(contains("\n")).getBefore());
        expect.sendLine("exit");
    } finally {
        expect.close();
        channel.disconnect();
        session.disconnect();
    }
}
 
Example #26
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
/**
 * 抓遠端檔案然後存到本機 , 多筆
 * 
 * @param user
 * @param password
 * @param addr
 * @param port
 * @param remoteFile
 * @param localFile
 * @throws JSchException
 * @throws SftpException
 * @throws Exception
 */
public static void get(String user, String password, String addr, int port, 
		List<String> remoteFile, List<String> localFile) throws JSchException, SftpException, Exception {
			
	Session session = getSession(user, password, addr, port);	
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;		
	try {
		for (int i=0; i<remoteFile.size(); i++) {
			String rf=remoteFile.get(i);
			String lf=localFile.get(i);
			logger.info("get remote file: " + rf + " write to:" + lf );
			sftpChannel.get(rf, lf);
			File f=new File(lf);
			if (!f.exists()) {
				f=null;
				logger.error("get remote file:"+rf + " fail!");
				throw new Exception("get remote file:"+rf + " fail!");
			}
			f=null;
			logger.info("success write:" + lf);
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();				
	}
}
 
Example #27
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
/**
 * 抓遠端檔案然後存到本機 , 單筆
 * 
 * @param user
 * @param password
 * @param addr
 * @param port
 * @param remoteFile
 * @param localFile
 * @throws JSchException
 * @throws SftpException
 * @throws Exception
 */
public static void get(String user, String password, String addr, int port, 
		String remoteFile, String localFile) throws JSchException, SftpException, Exception {
			
	Session session = getSession(user, password, addr, port);
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;		
	logger.info("get remote file: " + remoteFile + " write to:" + localFile );	
	try {
		sftpChannel.get(remoteFile, localFile);
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();			
	}
	File f=new File(localFile);
	if (!f.exists()) {
		f=null;
		logger.error("get remote file:"+remoteFile + " fail!");
		throw new Exception("get remote file:"+remoteFile + " fail!");
	}
	f=null;
	logger.info("success write:" + localFile);
}
 
Example #28
Source File: WebSSHServiceImpl.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
private void connectToSSH(SSHConnectInfo sshConnectInfo, WebSSHData webSSHData, ServerSource serverSource, Session webSocketSession, String httpSessionId) throws JSchException, IOException {
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
      com.jcraft.jsch.Session session = sshConnectInfo.getjSch().getSession(serverSource.getUserName(), serverSource.getIp(), serverSource.getPort());
      session.setConfig(config);
UserInfo ui = null;
if(StringUtils.isEmpty(serverSource.getSecretKey())) {
	ui = new SSHUserInfo(serverSource.getPwd());
} else {
	ui = new SSHGoogleAuthUserInfo(serverSource.getSecretKey(), serverSource.getPwd());
}
session.setUserInfo(ui);
      session.connect(6000);
      
      
      Channel channel = session.openChannel("shell");
      ((ChannelShell)channel).setPtyType("vt100", webSSHData.getCols(), webSSHData.getRows(), webSSHData.getTerminalWidth(), webSSHData.getTerminalHeight());
      channel.connect(5000);
      sshConnectInfo.setChannel(channel);

      transToSSH(channel, Constants.LINUX_ENTER);

      InputStream inputStream = channel.getInputStream();
      try {
          byte[] buffer = new byte[1024];
          int i = 0;
          while ((i = inputStream.read(buffer)) != -1) {
              sendMessage(webSocketSession, Arrays.copyOfRange(buffer, 0, i), httpSessionId);
          }

      } finally {
          session.disconnect();
          channel.disconnect();
          if (inputStream != null) {
              inputStream.close();
          }
      }

  }
 
Example #29
Source File: ConnectionManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Channel openChannel(String type) throws JSchException, InterruptedException, JSchException {
    try {
        return ConnectionManagerAccessor.getDefault().openAndAcquireChannel(env, type, true);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}
 
Example #30
Source File: WebSSHServiceImpl.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
private void transToSSH(Channel channel, String command) throws IOException {
    if (channel != null) {
        OutputStream outputStream = channel.getOutputStream();
        outputStream.write(command.getBytes());
        outputStream.flush();
    }
}