Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Constante que representa un enter.
- */
- private static final String ENTER_KEY = " ";
- /**
- * Sesión SSH establecida.
- */
- private Session session;
- private static final String USERNAME = "user";
- private static final String HOST = "10.00.00";
- private static final int PORT = 22;
- private static final String PASSWORD = "pass";
- public void connect(String username, String password, String host, int port)
- throws JSchException, IllegalAccessException {
- if (this.session == null || !this.session.isConnected()) {
- JSch jsch = new JSch();
- this.session = jsch.getSession(username, host, port);
- this.session.setPassword(password);
- // Parametro para no validar key de conexion.
- this.session.setConfig("StrictHostKeyChecking", "no");
- this.session.connect();
- } else {
- throw new IllegalAccessException("Sesion SSH ya iniciada.");
- }
- }
- public final String executeCommand(String command)
- throws IllegalAccessException, JSchException, IOException {
- if (this.session != null && this.session.isConnected()) {
- // Abrimos un canal SSH. Es como abrir una consola.
- ChannelExec channelExec = (ChannelExec) this.session.
- openChannel("exec");
- InputStream in = channelExec.getInputStream();
- // Ejecutamos el comando.
- channelExec.setCommand(command);
- channelExec.connect();
- // Obtenemos el texto impreso en la consola.
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- StringBuilder builder = new StringBuilder();
- String linea;
- while ((linea = reader.readLine()) != null) {
- builder.append(linea);
- builder.append(ENTER_KEY);
- }
- // Cerramos el canal SSH.
- channelExec.disconnect();
- // Retornamos el texto impreso en la consola.
- return builder.toString();
- } else {
- throw new IllegalAccessException("No existe sesion SSH iniciada.");
- }
- }
- public static void main(String[] args) {
- try {
- SSHConnector sshConnector = new SSHConnector();
- sshConnector.connect(USERNAME, PASSWORD, HOST, PORT);
- **String result = sshConnector.executeCommand("cd home/recauser/procesos/orquestador/bin;./startOrquestador.sh start");**
- sshConnector.disconnect();
- System.out.println(result);
- } catch (JSchException ex) {
- ex.printStackTrace();
- System.out.println(ex.getMessage());
- } catch (IllegalAccessException ex) {
- ex.printStackTrace();
- System.out.println(ex.getMessage());
- }
- catch (IOException ex) {
- ex.printStackTrace();
- System.out.println(ex.getMessage());
- }
- }
- /**
- * Cierra la sesión SSH.
- */
- public final void disconnect() {
- this.session.disconnect();
- }
Add Comment
Please, Sign In to add comment