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

The following examples show how to use com.jcraft.jsch.Channel#connect() . 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
@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 2
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 3
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 4
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 5
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 6
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 7
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 8
Source File: JschServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link ChannelShell}
 *
 * @param channelSessionKey the session key that identifies the channel
 * @return {@link ChannelShell}
 * @throws Exception thrown by borrowObject and invalidateObject
 */
private ChannelShell getChannelShell(final ChannelSessionKey channelSessionKey) throws Exception {
    final long startTime = System.currentTimeMillis();
    Channel channel;
    do {
        LOGGER.debug("borrowing a channel...");
        channel = channelPool.borrowObject(channelSessionKey);
        if (channel != null) {
            LOGGER.debug("channel {} borrowed", channel.getId());
            if (!channel.isConnected()) {
                try {
                    LOGGER.debug("channel {} connecting...", channel.getId());
                    channel.connect(CHANNEL_CONNECT_TIMEOUT);
                    LOGGER.debug("channel {} connected!", channel.getId());
                } catch (final JSchException jsche) {
                    LOGGER.error("Borrowed channel {} connection failed! Invalidating the channel...",
                            channel.getId(), jsche);
                    channelPool.invalidateObject(channelSessionKey, channel);
                }
            } else {
                LOGGER.debug("Channel {} already connected!", channel.getId());
            }
        }

        if ((channel == null || !channel.isConnected()) && (System.currentTimeMillis() - startTime) > CHANNEL_BORROW_LOOP_WAIT_TIME) {
            final String errMsg = MessageFormat.format("Failed to get a channel within {0} ms! Aborting channel acquisition!",
                    CHANNEL_BORROW_LOOP_WAIT_TIME);
            LOGGER.error(errMsg);
            throw new JschServiceException(errMsg);
        }
    } while (channel == null || !channel.isConnected());
    return (ChannelShell) channel;
}
 
Example 9
Source File: SshProxyTest.java    From jsch-extension with MIT License 5 votes vote down vote up
@Test
public void testSshProxy() {
    Proxy proxy = null;
    Session session = null;
    Channel channel = null;
    try {
        SessionFactory proxySessionFactory = sessionFactory.newSessionFactoryBuilder()
                .setHostname( "localhost" ).setPort( SessionFactory.SSH_PORT ).build();
        SessionFactory destinationSessionFactory = sessionFactory.newSessionFactoryBuilder()
                .setProxy( new SshProxy( proxySessionFactory ) ).build();
        session = destinationSessionFactory.newSession();

        session.connect();

        channel = session.openChannel( "exec" );
        ((ChannelExec)channel).setCommand( "echo " + expected );
        InputStream inputStream = channel.getInputStream();
        channel.connect();

        // echo adds \n
        assertEquals( expected + "\n", IOUtils.copyToString( inputStream, UTF8 ) );
    }
    catch ( Exception e ) {
        logger.error( "failed for proxy {}: {}", proxy, e );
        logger.debug( "failed:", e );
        fail( e.getMessage() );
    }
    finally {
        if ( channel != null && channel.isConnected() ) {
            channel.disconnect();
        }
        if ( session != null && session.isConnected() ) {
            session.disconnect();
        }
    }
}
 
Example 10
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 11
Source File: SshLocalhostExample.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("pwd");
        System.out.println(
                "pwd1:" + expect.expect(times(2, contains("\n")))
                        .getResults()
                        .get(1)
                        .getBefore());
        expect.sendLine("pwd");
        // a regexp which captures the output of pwd
        System.out.println("pwd2:" + expect.expect(regexp("(?m)\\n([^\\n]*)\\n")).group(1));
        expect.expect(contains("$"));
        expect.sendLine("ls -l");
        // skipping the echo command
        expect.expect(times(2, contains("\n")));
        // getting the output of ls
        System.out.println(expect.expect(regexp(".*\\$")).getBefore().trim());
        expect.sendLine("exit");
    } finally {
        expect.close();
        channel.disconnect();
        session.disconnect();
    }
}
 
Example 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
Source File: CommandDelegatorMethods.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
	 * Called from class:HadoopLogParser(method:checkAndgetCurrentLogFilePathForYarn),class: ClusterProfilingHelper (method: getJobDetails),Class CopyThread(run method)
	 * @param command
	 * @throws JSchException
	 * @throws IOException
	 */
	public void executeRemoteCommandAsSudo(Command command) throws JSchException, IOException
	{
	    Session session = null;
	    Channel channel = null;
	    String host = RemotingConstants.LOCALHOST;
	    SwitchedIdentity switchedIdentity = command.getSwitchedIdentity();
		CommandType commandType = command.getCommandType();
	    try {
			session = createSession(switchedIdentity, host, commandType);
	        channel = session.openChannel("exec");
	        String sudoCommand = "sudo -E su - " + switchedIdentity.getWorkingUser();
	        ((ChannelExec) channel).setCommand(sudoCommand);
	        ((ChannelExec) channel).setPty(true);
	        channel.connect();
	        InputStream inputStream = channel.getInputStream();
	        OutputStream out = channel.getOutputStream();
	        ((ChannelExec) channel).setErrStream(System.err);
	        if(switchedIdentity.getPrivatePath() == null || switchedIdentity.getPrivatePath().isEmpty()){
	        	out.write((StringUtil.getPlain(switchedIdentity.getPasswd()) + "\n").getBytes());
	        }
	        out.flush();
	        Thread.sleep(100);
			LOGGER.debug("Now Sending Command ["+command.getCommandString()+"]");
	        out.write((command.getCommandString() + "\n").getBytes());
	        out.flush();
	        Thread.sleep(100 * 100);
	        out.write(("logout" + "\n").getBytes());
	        out.flush();
	        Thread.sleep(100);
	        out.write(("exit" + "\n").getBytes());
/*			if(channel.getExitStatus()!=0){
				String errorDebug = logJsch(channel, inputStream);
				LOGGER.error("Detailed Debug log for Errored command [" + command.getCommandString() +"]\n ----- \n"+errorDebug+"\n-----");
			}	        
*/	        out.flush();
	        out.close();
	    } catch (Exception e) {
	        LOGGER.error(e.getCause());
	    } finally {
	    	if(session!=null){
				session.disconnect();
	    	}
	    	if(channel!=null){
	    		channel.disconnect();
	    	}
	    }
	}
 
Example 20
Source File: RmtShellExecutor.java    From LuckyFrameClient with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * ����JSch��ʵ��Զ������SHELL����ִ��
 *
 * @param ip      ����IP
 * @param user    ������½�û���
 * @param psw     ������½����
 * @param port    ����ssh2��½�˿ڣ����ȡĬ��ֵ����-1
 * @param command Shell����   cd /home/pospsettle/tomcat-7.0-7080/bin&&./restart.sh
 */
public static String sshShell(String ip, String user, String psw
        , int port, String command) {

    Session session = null;
    Channel channel = null;
    String result = "Status:true" + " ��������ִ�гɹ���";
    try {
        JSch jsch = new JSch();
        LogUtil.APP.info("���뵽����TOMCAT����...");

        if (port <= 0) {
            //���ӷ�����������Ĭ�϶˿�
            LogUtil.APP.info("��������TOMCAT������IP��Ĭ�϶˿�...");
            session = jsch.getSession(user, ip);
        } else {
            //����ָ���Ķ˿����ӷ�����
            LogUtil.APP.info("��������TOMCAT������IP���˿�...");
            session = jsch.getSession(user, ip, port);
            LogUtil.APP.info("��������TOMCAT������IP���˿����!");
        }

        //������������Ӳ��ϣ����׳��쳣
        if (session == null) {
            LogUtil.APP.warn("����TOMCAT�����У����ӷ�����session is null");
            throw new Exception("session is null");
        }
        //���õ�½����������
        session.setPassword(psw);
        //���õ�һ�ε�½��ʱ����ʾ����ѡֵ��(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //���õ�½��ʱʱ��
        session.connect(30000);

        //����sftpͨ��ͨ��
        channel = session.openChannel("shell");
        channel.connect(1000);

        //��ȡ�������������
        InputStream instream = channel.getInputStream();
        OutputStream outstream = channel.getOutputStream();

        //������Ҫִ�е�SHELL�����Ҫ��\n��β����ʾ�س�
        LogUtil.APP.info("׼��������TOMCAT��������������!");
        String shellCommand = command + "  \n";
        outstream.write(shellCommand.getBytes());
        outstream.flush();

        Thread.sleep(10000);
        //��ȡ����ִ�еĽ��
        if (instream.available() > 0) {
            byte[] data = new byte[instream.available()];
            int nLen = instream.read(data);
            if (nLen < 0) {
                LogUtil.APP.warn("����TOMCAT�����У���ȡ����ִ�н�������쳣��");
            }

            //ת������������ӡ����
            String temp = new String(data, 0, nLen, "iso8859-1");
            LogUtil.APP.info("��ʼ��ӡ����TOMCAT����ִ�н��...{}", temp);
        }
        outstream.close();
        instream.close();
    } catch (Exception e) {
        result = "����TOMCAT�����У������쳣��";
        LogUtil.APP.error("����TOMCAT�����У������쳣��", e);
        return result;
    } finally {
        if (null != session) {
            session.disconnect();
        }
        if (null != channel) {
            channel.disconnect();
        }

    }
    return result;
}