Java Code Examples for com.jcraft.jsch.ChannelExec#disconnect()

The following examples show how to use com.jcraft.jsch.ChannelExec#disconnect() . 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: RemoteLauncherCommands.java    From gemfirexd-oss with Apache License 2.0 8 votes vote down vote up
/**
 * Connect to a remote host via SSH and execute a command.
 * 
 * @param host
 *          Host to connect to
 * @param user
 *          User to login with
 * @param password
 *          Password for the user
 * @param command
 *          Command to execute
 * @return The result of the command execution
 */
private Result executeSshCommand(final String host, final String user,
    final String password, final String command) {
  
  StringBuilder result = new StringBuilder();
  
  try {
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host, 22);
    session.setUserInfo(createUserInfo(password));
    session.connect(5000);

    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(command);
    channel.setInputStream(null);
    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;
        result.append(new String(tmp, 0, i));
      }
      if (channel.isClosed()) {
        break;
      }
    }
    channel.disconnect();
    session.disconnect();
  } catch (Exception jex) {
    return createResult(Result.Status.ERROR, jex.getMessage());
  }
 
  return createResult(Result.Status.OK, result.toString());
}
 
Example 2
Source File: SSHPushWorker.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Wait for a given {@link ChannelExec} to be closed.
 * Will close channel if maxWait is set and exceeded.
 * @param channel the channel
 */
private void waitForChannelClosed(ChannelExec channel) {
    long startTime = System.currentTimeMillis();
    while (!channel.isClosed()) {
        // Check to see if we have been waiting too long, converts ms to minutes
        long elapsedTimeInMins =
                TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - startTime);
        if (maxWait > 0 && elapsedTimeInMins > maxWait) {
            log.error("Task took too long to complete");
            channel.disconnect();
        }
        try {
            Thread.sleep(1000);
        }
        catch (InterruptedException e) {
            // Should not happen
        }
    }
}
 
Example 3
Source File: DeploymentEngine.java    From if1007 with MIT License 6 votes vote down vote up
private boolean executeSSH(){ 
	//get deployment descriptor, instead of this hard coded.
	// or execute a script on the target machine which download artifact from nexus
       String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &";
      try{	
   	   System.out.println("Executing "+ command);
          java.util.Properties config = new java.util.Properties(); 
          config.put("StrictHostKeyChecking", "no");
          JSch jsch = new JSch();
          Session session=jsch.getSession("rajeshrv", "localhost", 22);
          session.setPassword("rajeshrv");
          
          session.setConfig(config);
          session.connect();
          System.out.println("Connected");
           
          ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
          InputStream in = channelExec.getInputStream();
          channelExec.setCommand(command);
          channelExec.connect();
         
          BufferedReader reader = new BufferedReader(new InputStreamReader(in));
          String line;
          int index = 0;

          while ((line = reader.readLine()) != null) {
              System.out.println(++index + " : " + line);
          }
          channelExec.disconnect();
          session.disconnect();

          System.out.println("Done!");

      }catch(Exception e){
          e.printStackTrace();
          return false;
      }
	
	return true;
}
 
Example 4
Source File: Scp.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
/**
 * Initiates an SCP sequence but stops after getting fileinformation header
 *
 * @param remoteFile
 *            to get information for
 * @return the file information got
 * @throws IOException
 *             in case of network problems
 * @throws RemoteScpException
 *             in case of problems on the target system (connection ok)
 */
public FileInfo getFileinfo(String remoteFile) throws IOException, RemoteScpException {
    ChannelExec channel = null;
    FileInfo fileInfo = null;

    if (remoteFile == null) {
        throw new IllegalArgumentException("Null argument.");
    }

    String cmd = "scp -p -f \"" + remoteFile + "\"";

    try {
        channel = getExecChannel();
        channel.setCommand(cmd);
        fileInfo = receiveStream(channel, remoteFile, null);
        channel.disconnect();
    } catch (JSchException e) {
        throw new IOException("Error during SCP transfer. " + e.getMessage(), e);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
    return fileInfo;
}
 
Example 5
Source File: Scp.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
/**
 * Download a file from the remote server into an OutputStream
 *
 * @param remoteFile
 *            Path and name of the remote file.
 * @param localTarget
 *            OutputStream to store the data.
 * @throws IOException
 *             in case of network problems
 * @throws RemoteScpException
 *             in case of problems on the target system (connection ok)
 */
@SuppressWarnings("unused")
public void get(String remoteFile, OutputStream localTarget) throws IOException,
        RemoteScpException {
    ChannelExec channel = null;

    if (remoteFile == null || localTarget == null) {
        throw new IllegalArgumentException("Null argument.");
    }

    String cmd = "scp -p -f " + remoteFile;

    try {
        channel = getExecChannel();
        channel.setCommand(cmd);
        receiveStream(channel, remoteFile, localTarget);
        channel.disconnect();
    } catch (JSchException e) {
        if (channel != null) {
            channel.disconnect();
        }
        throw new IOException("Error during SCP transfer. " + e.getMessage(), e);
    }
}
 
Example 6
Source File: SSHHandlerTarget.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Force create directories, if it exists it won't do anything
 *
 * @param path
 * @throws IOException
 * @throws RuntimeConfigurationException
 */
private void forceCreateDirectories(@NotNull final String path) throws IOException, RuntimeConfigurationException {
    Session session = connect(ssh.get());
    try {
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        List<String> commands = Arrays.asList(
                String.format("mkdir -p %s", path),
                String.format("cd %s", path),
                String.format("mkdir -p %s", FileUtilities.CLASSES),
                String.format("mkdir -p %s", FileUtilities.LIB),
                String.format("cd %s", path + FileUtilities.SEPARATOR + FileUtilities.CLASSES),
                "rm -rf *"
        );
        for (String command : commands) {
            consoleView.print(EmbeddedLinuxJVMBundle.getString("pi.deployment.command") + command + NEW_LINE, ConsoleViewContentType.SYSTEM_OUTPUT);
        }
        channelExec.setCommand(LinuxCommand.builder().commands(commands).build().toString());
        channelExec.connect();
        channelExec.disconnect();
    } catch (JSchException e) {
        setErrorOnUI(e.getMessage());
    }
}
 
Example 7
Source File: SftpFileSystemWindows.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 *
 * {@link  org.apache.commons.vfs2.provider.sftp.SftpFileSystem#executeCommand(java.lang.String, java.lang.StringBuilder) }
 */
private int executeCommand( String command, StringBuilder output ) throws JSchException, IOException {
  this.ensureSession();
  ChannelExec channel = (ChannelExec) this.session.openChannel( "exec" );
  channel.setCommand( command );
  channel.setInputStream( (InputStream) null );
  InputStreamReader stream = new InputStreamReader( channel.getInputStream() );
  channel.setErrStream( System.err, true );
  channel.connect();
  char[] buffer = new char[128];

  int read;
  while ( ( read = stream.read( buffer, 0, buffer.length ) ) >= 0 ) {
    output.append( buffer, 0, read );
  }

  stream.close();

  while ( !channel.isClosed() ) {
    try {
      Thread.sleep( 100L );
    } catch ( Exception exc ) {
      log.logMinimal( "Warning: Error session closing. " + exc.getMessage() );
    }
  }

  channel.disconnect();
  return channel.getExitStatus();
}
 
Example 8
Source File: SftpFileSystem.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a command and returns the (standard) output through a StringBuilder.
 *
 * @param command The command
 * @param output  The output
 * @return The exit code of the command
 * @throws JSchException       if a JSch error is detected.
 * @throws FileSystemException if a session cannot be created.
 * @throws IOException         if an I/O error is detected.
 */
private int executeCommand(final String command, final StringBuilder output) throws JSchException, IOException {
    final ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
    try {
        channel.setCommand(command);
        channel.setInputStream(null);
        try (final InputStreamReader stream = new InputStreamReader(channel.getInputStream())) {
            channel.setErrStream(System.err, true);
            channel.connect(connectTimeoutMillis);

            // Read the stream
            final char[] buffer = new char[EXEC_BUFFER_SIZE];
            int read;
            while ((read = stream.read(buffer, 0, buffer.length)) >= 0) {
                output.append(buffer, 0, read);
            }
        }

        // Wait until the command finishes (should not be long since we read the output stream)
        while (!channel.isClosed()) {
            try {
                Thread.sleep(SLEEP_MILLIS);
            } catch (final Exception ee) {
                // TODO: swallow exception, really?
            }
        }
    } finally {
        channel.disconnect();
    }
    return channel.getExitStatus();
}
 
Example 9
Source File: RemoteCredentialsSupport.java    From kork with Apache License 2.0 5 votes vote down vote up
static RemoteCredentials getRemoteCredentials(
    String command, String user, String host, int port) {

  RemoteCredentials remoteCredentials = new RemoteCredentials();

  try {
    Session session = jsch.getSession(user, host, port);
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    config.put("PreferredAuthentications", "publickey");
    config.put("HashKnownHosts", "yes");

    session.setConfig(config);
    session.setPassword("");
    session.connect();

    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    InputStream is = channel.getInputStream();

    channel.setCommand(command);
    channel.connect();

    String output = IOUtils.toString(is);
    log.debug("Remote credentials: {}", output);

    channel.disconnect();
    session.disconnect();

    output = output.replace("\n", "");
    remoteCredentials = objectMapper.readValue(output, RemoteCredentials.class);
  } catch (Exception e) {
    log.error("Remote SSH execution failed.", e);
  }

  return remoteCredentials;
}
 
Example 10
Source File: SshRepository.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to create a directory path on the target system
 *
 * @param path
 *            to create
 * @param session
 *            to use
 */
private void makePath(String path, Session session) throws IOException {
    ChannelExec channel = null;
    String trimmed = path;
    try {
        while (trimmed.length() > 0 && trimmed.charAt(trimmed.length() - 1) == fileSeparator) {
            trimmed = trimmed.substring(0, trimmed.length() - 1);
        }
        if (trimmed.length() == 0 || checkExistence(trimmed, session)) {
            return;
        }
        int nextSlash = trimmed.lastIndexOf(fileSeparator);
        if (nextSlash > 0) {
            String parent = trimmed.substring(0, nextSlash);
            makePath(parent, session);
        }
        channel = getExecChannel(session);
        String mkdir = replaceArgument(createDirCommand, trimmed);
        Message.debug("SShRepository: trying to create path: " + mkdir);
        channel.setCommand(mkdir);
        StringBuilder stdOut = new StringBuilder();
        StringBuilder stdErr = new StringBuilder();
        readSessionOutput(channel, stdOut, stdErr);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
 
Example 11
Source File: RemoteLauncherCommands.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to a remote host via SSH and execute a command.
 * 
 * @param host
 *          Host to connect to
 * @param user
 *          User to login with
 * @param password
 *          Password for the user
 * @param command
 *          Command to execute
 * @return The result of the command execution
 */
private Result executeSshCommand(final String host, final String user,
    final String password, final String command) {
  
  StringBuilder result = new StringBuilder();
  
  try {
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host, 22);
    session.setUserInfo(createUserInfo(password));
    session.connect(5000);

    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(command);
    channel.setInputStream(null);
    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;
        result.append(new String(tmp, 0, i));
      }
      if (channel.isClosed()) {
        break;
      }
    }
    channel.disconnect();
    session.disconnect();
  } catch (Exception jex) {
    return createResult(Result.Status.ERROR, jex.getMessage());
  }
 
  return createResult(Result.Status.OK, result.toString());
}
 
Example 12
Source File: DeploymentEngine.java    From Spring-Microservices with MIT License 5 votes vote down vote up
private boolean executeSSH(){ 
	//get deployment descriptor, instead of this hard coded.
	// or execute a script on the target machine which download artifact from nexus
       String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &";
      try{	
   	   System.out.println("Executing "+ command);
          java.util.Properties config = new java.util.Properties(); 
          config.put("StrictHostKeyChecking", "no");
          JSch jsch = new JSch();
          Session session=jsch.getSession("rajeshrv", "localhost", 22);
          session.setPassword("rajeshrv");
          
          session.setConfig(config);
          session.connect();
          System.out.println("Connected");
           
          ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
          InputStream in = channelExec.getInputStream();
          channelExec.setCommand(command);
          channelExec.connect();
         
          BufferedReader reader = new BufferedReader(new InputStreamReader(in));
          String line;
          int index = 0;

          while ((line = reader.readLine()) != null) {
              System.out.println(++index + " : " + line);
          }
          channelExec.disconnect();
          session.disconnect();

          System.out.println("Done!");

      }catch(Exception e){
          e.printStackTrace();
          return false;
      }
	
	return true;
}
 
Example 13
Source File: DeploymentEngine.java    From Microservices-Building-Scalable-Software with MIT License 5 votes vote down vote up
private boolean executeSSH(){ 
	//get deployment descriptor, instead of this hard coded.
	// or execute a script on the target machine which download artifact from nexus
       String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &";
      try{	
   	   System.out.println("Executing "+ command);
          java.util.Properties config = new java.util.Properties(); 
          config.put("StrictHostKeyChecking", "no");
          JSch jsch = new JSch();
          Session session=jsch.getSession("rajeshrv", "localhost", 22);
          session.setPassword("rajeshrv");
          
          session.setConfig(config);
          session.connect();
          System.out.println("Connected");
           
          ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
          InputStream in = channelExec.getInputStream();
          channelExec.setCommand(command);
          channelExec.connect();
         
          BufferedReader reader = new BufferedReader(new InputStreamReader(in));
          String line;
          int index = 0;

          while ((line = reader.readLine()) != null) {
              System.out.println(++index + " : " + line);
          }
          channelExec.disconnect();
          session.disconnect();

          System.out.println("Done!");

      }catch(Exception e){
          e.printStackTrace();
          return false;
      }
	
	return true;
}
 
Example 14
Source File: SshFenceByTcpPort.java    From big-c with Apache License 2.0 5 votes vote down vote up
private static void cleanup(ChannelExec exec) {
  if (exec != null) {
    try {
      exec.disconnect();
    } catch (Throwable t) {
      LOG.warn("Couldn't disconnect ssh channel", t);
    }
  }
}
 
Example 15
Source File: SshFenceByTcpPort.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private static void cleanup(ChannelExec exec) {
  if (exec != null) {
    try {
      exec.disconnect();
    } catch (Throwable t) {
      LOG.warn("Couldn't disconnect ssh channel", t);
    }
  }
}
 
Example 16
Source File: JschSshClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param command SSH command to execute
 * @return the exit code
 */
public int execute( String command, boolean waitForCompletion ) {

    try {
        this.command = command;

        execChannel = (ChannelExec) session.openChannel("exec");

        execChannel.setCommand(command);
        execChannel.setInputStream(null);
        execChannel.setPty(true); // Allocate a Pseudo-Terminal. Thus it supports login sessions. (eg. /bin/bash
                                  // -l)

        execChannel.connect(); // there is a bug in the other method channel.connect( TIMEOUT );

        stdoutThread = new StreamReader(execChannel.getInputStream(), execChannel, "STDOUT");
        stderrThread = new StreamReader(execChannel.getErrStream(), execChannel, "STDERR");
        stdoutThread.start();
        stderrThread.start();

        if (waitForCompletion) {

            stdoutThread.getContent();
            stderrThread.getContent();
            return execChannel.getExitStatus();
        }

    } catch (Exception e) {

        throw new JschSshClientException(e.getMessage(), e);
    } finally {

        if (waitForCompletion && execChannel != null) {
            execChannel.disconnect();
        }
    }

    return -1;
}
 
Example 17
Source File: Scp.java    From ant-ivy with Apache License 2.0 4 votes vote down vote up
/**
 * Copy a local file to a remote site, uses the specified mode when creating the file on the
 * remote side.
 *
 * @param localFile
 *            Path and name of local file. Must be absolute.
 * @param remoteTargetDir
 *            Remote target directory where the file has to end up (optional)
 * @param remoteTargetName
 *            file name to use on the target system
 * @param mode
 *            a four digit string (e.g., 0644, see "man chmod", "man open")
 * @throws IOException
 *             in case of network problems
 * @throws RemoteScpException
 *             in case of problems on the target system (connection ok)
 */
@SuppressWarnings("unused")
public void put(String localFile, String remoteTargetDir, String remoteTargetName, String mode)
        throws IOException, RemoteScpException {
    ChannelExec channel = null;

    if (localFile == null || remoteTargetName == null) {
        throw new IllegalArgumentException("Null argument.");
    }

    if (mode != null) {
        if (mode.length() != MODE_LENGTH) {
            throw new IllegalArgumentException("Invalid mode.");
        }

        for (char c : mode.toCharArray()) {
            if (!Character.isDigit(c)) {
                throw new IllegalArgumentException("Invalid mode.");
            }
        }
    }

    String cmd = "scp -t ";
    if (mode != null) {
        cmd += "-p ";
    }
    if (remoteTargetDir != null && remoteTargetDir.length() > 0) {
        cmd += "-d " + remoteTargetDir;
    }

    try {
        channel = getExecChannel();
        channel.setCommand(cmd);
        sendFile(channel, localFile, remoteTargetName, mode);
        channel.disconnect();
    } catch (JSchException e) {
        if (channel != null) {
            channel.disconnect();
        }
        throw new IOException("Error during SCP transfer." + e.getMessage(), e);
    }
}
 
Example 18
Source File: GitRepo.java    From warnings-ng-plugin with MIT License 4 votes vote down vote up
/**
 * Zip bare repository, copy to Docker container using sftp, then unzip. The repo is now accessible over
 * "ssh://git@ip:port/home/git/gitRepo.git"
 *
 * @param host
 *         IP of Docker container
 * @param port
 *         SSH port of Docker container
 */
public void transferToDockerContainer(String host, int port) {
    try {
        Path zipPath = Files.createTempFile("git", "zip");
        File zippedRepo = zipPath.toFile();
        String zippedFilename = zipPath.getFileName().toString();
        ZipUtil.pack(new File(dir.getPath()), zippedRepo);

        Properties props = new Properties();
        props.put("StrictHostKeyChecking", "no");

        JSch jSch = new JSch();
        jSch.addIdentity(privateKey.getAbsolutePath());

        Session session = jSch.getSession("git", host, port);
        session.setConfig(props);
        session.connect();

        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        channel.cd("/home/git");
        channel.put(new FileInputStream(zippedRepo), zippedFilename);

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand("unzip " + zippedFilename + " -d " + REPO_NAME);
        channelExec.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        int index = 0;
        while ((line = reader.readLine()) != null) {
            System.out.println(++index + " : " + line);
        }

        channelExec.disconnect();
        channel.disconnect();
        session.disconnect();
        // Files.delete(zipPath);
    }
    catch (IOException | JSchException | SftpException e) {
        throw new AssertionError("Can't transfer git repository to docker container", e);
    }
}