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

The following examples show how to use com.jcraft.jsch.Channel#getInputStream() . 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 7 votes vote down vote up
@Test
public void testWrite() throws Exception {
  termHandler = term -> {
    term.write("hello");
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  Reader in = new InputStreamReader(channel.getInputStream());
  int count = 5;
  StringBuilder sb = new StringBuilder();
  while (count > 0) {
    int code = in.read();
    if (code == -1) {
      count = 0;
    } else {
      count--;
      sb.append((char) code);
    }
  }
  assertEquals("hello", sb.toString());
  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 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 3
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 4
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 5
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 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 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 7
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 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: JschServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Override
public RemoteCommandReturnInfo runShellCommand(RemoteSystemConnection remoteSystemConnection, String command, long timeout) {
    final ChannelSessionKey channelSessionKey = new ChannelSessionKey(remoteSystemConnection, ChannelType.SHELL);
    LOGGER.debug("channel session key = {}", channelSessionKey);
    Channel channel = null;
    try {
        channel = getChannelShell(channelSessionKey);

        final InputStream in = channel.getInputStream();
        final OutputStream out = channel.getOutputStream();

        LOGGER.debug("Executing command \"{}\"", command);
        out.write(command.getBytes(StandardCharsets.UTF_8));
        out.write(CRLF.getBytes(StandardCharsets.UTF_8));
        out.write("echo 'EXIT_CODE='$?***".getBytes(StandardCharsets.UTF_8));
        out.write(CRLF.getBytes(StandardCharsets.UTF_8));
        out.write("echo -n -e '\\xff'".getBytes(StandardCharsets.UTF_8));
        out.write(CRLF.getBytes(StandardCharsets.UTF_8));
        out.flush();

        return getShellRemoteCommandReturnInfo(command, in, timeout);
    } catch (final Exception e) {
        final String errMsg = MessageFormat.format("Failed to run the following command: {0}", command);
        LOGGER.error(errMsg, e);
        throw new JschServiceException(errMsg, e);
    } finally {
        if (channel != null) {
            channelPool.returnObject(channelSessionKey, channel);
            LOGGER.debug("channel {} returned", channel.getId());
        }
    }
}
 
Example 10
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 11
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 12
Source File: SSHManager.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public String sendCommand(String command) {
    StringBuilder outputBuffer = new StringBuilder();

    try {
        Channel channel = sesConnection.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        InputStream commandOutput = channel.getInputStream();
        channel.connect();
        int readByte = commandOutput.read();

        while (readByte != 0xffffffff) {
            outputBuffer.append((char) readByte);
            readByte = commandOutput.read();
        }
        channel.disconnect();
    } catch (IOException ioX) {
        logWarning(ioX.getMessage());
        LOGGER.error("error while getting kernelversion from SSH", ioX);
        return null;
    } catch (JSchException jschX) {
        LOGGER.error(
                "error while getting kernelversion from JSchException SSH",
                jschX);
        logWarning(jschX.getMessage());
        return null;
    }

    return outputBuffer.toString();
}
 
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: 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();
  }
}
 
Example 15
Source File: Scp.java    From ant-ivy with Apache License 2.0 4 votes vote down vote up
private void sendFile(Channel channel, String localFile, String remoteName, String mode)
        throws IOException, RemoteScpException {
    byte[] buffer = new byte[BUFFER_SIZE];

    OutputStream os = new BufferedOutputStream(channel.getOutputStream(),
            SEND_FILE_BUFFER_LENGTH);
    InputStream is = new BufferedInputStream(channel.getInputStream(), SEND_BYTES_BUFFER_LENGTH);

    try {
        if (channel.isConnected()) {
            channel.start();
        } else {
            channel.connect();
        }
    } catch (JSchException jsche) {
        throw new IOException("Channel connection problems", jsche);
    }

    readResponse(is);

    File f = new File(localFile);
    long remain = f.length();

    String cMode = mode;
    if (cMode == null) {
        cMode = "0600";
    }
    String cline = "C" + cMode + " " + remain + " " + remoteName + "\n";

    os.write(cline.getBytes());
    os.flush();

    readResponse(is);

    try (FileInputStream fis = new FileInputStream(f)) {
        while (remain > 0) {
            int trans;
            if (remain > buffer.length) {
                trans = buffer.length;
            } else {
                trans = (int) remain;
            }
            if (fis.read(buffer, 0, trans) != trans) {
                throw new IOException("Cannot read enough from local file " + localFile);
            }

            os.write(buffer, 0, trans);

            remain -= trans;
        }
    }

    os.write(0);
    os.flush();

    readResponse(is);

    os.write("E\n".getBytes());
    os.flush();
}
 
Example 16
Source File: Scp.java    From ant-ivy with Apache License 2.0 4 votes vote down vote up
/**
 * Receive a file via scp and store it in a stream
 *
 * @param channel
 *            ssh channel to use
 * @param file
 *            to receive from remote
 * @param targetStream
 *            to store file into (if null, get only file info)
 * @return file information of the file we received
 * @throws IOException
 *             in case of network or protocol trouble
 * @throws RemoteScpException
 *             in case of problems on the target system (connection is fine)
 */
private FileInfo receiveStream(Channel channel, String file, OutputStream targetStream)
        throws IOException, RemoteScpException {
    byte[] buffer = new byte[BUFFER_SIZE];

    OutputStream os = channel.getOutputStream();
    InputStream is = channel.getInputStream();
    try {
        if (channel.isConnected()) {
            channel.start();
        } else {
            channel.connect();
        }
    } catch (JSchException jsche) {
        throw new IOException("Channel connection problems", jsche);
    }
    os.write(0x0);
    os.flush();

    FileInfo fileInfo = new FileInfo();

    while (true) {
        int c = is.read();
        if (c < 0) {
            throw new RemoteScpException("Remote scp terminated unexpectedly.");
        }

        String line = receiveLine(is);

        if (c == 'T') {
            parseTLine(line, fileInfo);
            os.write(0x0);
            os.flush();
            continue;
        }
        if (c == 1 || c == 2) {
            throw new RemoteScpException("Remote SCP error: " + line);
        }

        if (c == 'C') {
            parseCLine(line, fileInfo);
            break;
        }
        throw new RemoteScpException("Remote SCP error: " + ((char) c) + line);
    }
    if (targetStream != null) {

        os.write(0x0);
        os.flush();

        try {
            long remain = fileInfo.getLength();

            while (remain > 0) {
                int trans;
                if (remain > buffer.length) {
                    trans = buffer.length;
                } else {
                    trans = (int) remain;
                }

                int thisTimeReceived = is.read(buffer, 0, trans);

                if (thisTimeReceived < 0) {
                    throw new IOException("Remote scp terminated connection unexpectedly");
                }

                targetStream.write(buffer, 0, thisTimeReceived);

                remain -= thisTimeReceived;
            }

            targetStream.close();
        } catch (IOException e) {
            if (targetStream != null) {
                targetStream.close();
            }
            throw (e);
        }

        readResponse(is);

        os.write(0x0);
        os.flush();
    }
    return fileInfo;
}
 
Example 17
Source File: SshRequestHandler.java    From trigger with GNU General Public License v2.0 4 votes vote down vote up
public void run() {
    if (setup.getId() < 0) {
        this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Internal Error");
        return;
    }

    if (setup.require_wifi && !WifiTools.isConnected()) {
        this.listener.onTaskResult(setup.getId(), ReplyCode.DISABLED, "Wifi Disabled.");
        return;
    }

    String command = "";

    switch (action) {
        case open_door:
            command = setup.open_command;
            break;
        case close_door:
            command = setup.close_command;
            break;
        case ring_door:
            command = setup.ring_command;
            break;
        case fetch_state:
            command = setup.state_command;
            break;
    }

    String user = setup.user;
    String password = setup.password;
    String host = setup.host;
    KeyPair keypair = setup.keypair;
    int port = setup.port;

    try {
        if (command.isEmpty()) {
            listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "");
            return;
        }

        if (host.isEmpty()) {
            listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Host is empty.");
            return;
        }

        // fallback
        if (setup.user.isEmpty()) {
            user = "root";
        }

        JSch jsch = new JSch();

        if (keypair != null) {
            SshTools.KeyPairData data = SshTools.keypairToBytes(keypair);
            byte passphrase[] = new byte[0];

            jsch.addIdentity("authkey", data.prvkey, data.pubkey, passphrase);
        }

        Session session = jsch.getSession(user, host, port);

        if (password.length() > 0) {
            session.setPassword(password);
        }

        session.setConfig("StrictHostKeyChecking", "no");

        StringBuilder outputBuffer = new StringBuilder();

        try {
            session.connect(5000); // 5sec timeout

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

            ((ChannelExec) channel).setCommand(command);
            InputStream commandOutput = channel.getInputStream();

            channel.connect();

            int readByte = commandOutput.read();

            while (readByte != 0xffffffff) {
               outputBuffer.append((char)readByte);
               readByte = commandOutput.read();
            }

            channel.disconnect();
            session.disconnect();
        } catch (IOException ioe) {
            listener.onTaskResult(setup.getId(), ReplyCode.REMOTE_ERROR, ioe.getMessage());
        } catch (JSchException jse) {
            listener.onTaskResult(setup.getId(), ReplyCode.REMOTE_ERROR, jse.getMessage());
        }

        listener.onTaskResult(setup.getId(), ReplyCode.SUCCESS, outputBuffer.toString());
    } catch (Exception e) {
        this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, e.toString());
    }
}
 
Example 18
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 19
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 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;
}