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

The following examples show how to use com.jcraft.jsch.ChannelExec#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: 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: SshExecutor.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Override
protected SshOutput executeCommand(ServerConfiguration serverConfig, Commands commands, ChannelExec channel)
        throws JSchException, IOException
{
    channel.setAgentForwarding(serverConfig.isAgentForwarding());
    SshOutput executionOutput = new SshOutput();
    try (ByteArrayOutputStream errorStream = new ByteArrayOutputStream())
    {
        channel.setCommand(commands.getJoinedCommands());
        channel.setErrStream(errorStream);
        channel.connect();
        executionOutput.setOutputStream(readChannelInputStream(channel));
        executionOutput.setErrorStream(new String(errorStream.toByteArray(), StandardCharsets.UTF_8));
        executionOutput.setExitStatus(channel.getExitStatus());
    }
    return executionOutput;
}
 
Example 3
Source File: SshConnectionImpl.java    From gerrit-events with MIT License 6 votes vote down vote up
/**
 * This version takes a command to run, and then returns a wrapper instance
 * that exposes all the standard state of the channel (stdin, stdout,
 * stderr, exit status, etc). Channel connection is established if establishConnection
 * is true.
 *
 * @param command the command to execute.
 * @param establishConnection true if establish channel connetction within this method.
 * @return a Channel with access to all streams and the exit code.
 * @throws IOException  if it is so.
 * @throws SshException if there are any ssh problems.
 * @see #executeCommandReader(String)
 */
@Override
public synchronized ChannelExec executeCommandChannel(String command, Boolean establishConnection)
        throws SshException, IOException {
    if (!isConnected()) {
        throw new IOException("Not connected!");
    }
    try {
        ChannelExec channel = (ChannelExec)connectSession.openChannel("exec");
        channel.setCommand(command);
        if (establishConnection) {
            channel.connect();
        }
        return channel;
    } catch (JSchException ex) {
        throw new SshException(ex);
    }
}
 
Example 4
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 5
Source File: SSHHandlerTarget.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Runs that java app with the specified command and then takes the console output from target to host machine
 *
 * @param path
 * @param cmd
 * @throws IOException
 */
private void runJavaApp(@NotNull final String path, @NotNull final String cmd) throws IOException, RuntimeConfigurationException {
    consoleView.print(NEW_LINE + EmbeddedLinuxJVMBundle.getString("pi.deployment.build") + NEW_LINE + NEW_LINE, ConsoleViewContentType.SYSTEM_OUTPUT);
    Session session = connect(ssh.get());
    consoleView.setSession(session);
    try {
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setOutputStream(System.out, true);
        channelExec.setErrStream(System.err, true);
        List<String> commands = Arrays.asList(
                String.format("%s kill -9 $(ps -efww | grep \"%s\"| grep -v grep | tr -s \" \"| cut -d\" \" -f2)", params.isRunAsRoot() ? "sudo" : "", params.getMainclass()),
                String.format("cd %s", path),
                String.format("tar -xvf %s.tar", consoleView.getProject().getName()),
                "rm *.tar",
                cmd);
        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();
        checkOnProcess(channelExec);
    } catch (JSchException e) {
        setErrorOnUI(e.getMessage());
    }
}
 
Example 6
Source File: Ssh.java    From BigDataScript with Apache License 2.0 5 votes vote down vote up
/**
 * Connect via ssh and execute a command (e.g. execute "ls -al" in remote host)
 *
 * Reference: http://www.jcraft.com/jsch/examples/Exec.java.html
 */
public String exec(String command) {
	// Open ssh session
	try {
		Gpr.debug("COMMAND: " + command);
		channel = connect("exec", command);
		ChannelExec chexec = (ChannelExec) channel;
		chexec.setInputStream(null);
		chexec.setPty(true); // Allocate pseudo-tty (same as "ssh -t")

		if (debug) {
			// Show only in debug mode
			chexec.setErrStream(System.err);
			chexec.setOutputStream(System.out);
		}

		// Connect channel
		chexec.connect();

		// Read input
		String result = readChannel(true);

		disconnect(false); // Disconnect and get exit code
		return result;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
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: SftpStreamProxy.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
@Override
public void connect(final SocketFactory socketFactory, final String targetHost, final int targetPort,
        final int timeout) throws Exception {
    session = SftpClientFactory.createConnection(proxyHost, proxyPort, proxyUser.toCharArray(),
            proxyPassword.toCharArray(), proxyOptions);
    channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(String.format(commandFormat, targetHost, targetPort));
    channel.connect(timeout);
}
 
Example 9
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 10
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 11
Source File: SshProvider.java    From parallec with Apache License 2.0 5 votes vote down vote up
/**
  * Session connect generate channel.
  *
  * @param session
  *            the session
  * @return the channel
  * @throws JSchException
  *             the j sch exception
  */
 public Channel sessionConnectGenerateChannel(Session session)
         throws JSchException {
 	// set timeout
     session.connect(sshMeta.getSshConnectionTimeoutMillis());
     
     ChannelExec channel = (ChannelExec) session.openChannel("exec");
     channel.setCommand(sshMeta.getCommandLine());

     // if run as super user, assuming the input stream expecting a password
     if (sshMeta.isRunAsSuperUser()) {
     	try {
             channel.setInputStream(null, true);

             OutputStream out = channel.getOutputStream();
             channel.setOutputStream(System.out, true);
             channel.setExtOutputStream(System.err, true);
             channel.setPty(true);
             channel.connect();
             
          out.write((sshMeta.getPassword()+"\n").getBytes());
          out.flush();
} catch (IOException e) {
	logger.error("error in sessionConnectGenerateChannel for super user", e);
}
     } else {
     	channel.setInputStream(null);
     	channel.connect();
     }

     return channel;

 }
 
Example 12
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 13
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 14
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 15
Source File: DeploymentEngine.java    From if1007 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 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: JschSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the specified command (executable + params) on the specified ExecutionEnvironment.
 *
 * @param env - environment to execute in
 * @param command - executable + params to execute
 * @param params - (optional) channel params. May be null.
 * @return I/O streams and opened execution JSch channel. Never returns NULL.
 * @throws IOException - if unable to aquire an execution channel
 * @throws JSchException - if JSch exception occured
 * @throws InterruptedException - if the thread was interrupted
 */
public static ChannelStreams startCommand(final ExecutionEnvironment env, final String command, final ChannelParams params)
        throws IOException, JSchException, InterruptedException {

    JSchWorker<ChannelStreams> worker = new JSchWorker<ChannelStreams>() {

        @Override
        public ChannelStreams call() throws JSchException, IOException, InterruptedException {
            ChannelExec echannel = (ChannelExec) ConnectionManagerAccessor.getDefault().openAndAcquireChannel(env, "exec", true); // NOI18N

            if (echannel == null) {
                throw new IOException("Cannot open exec channel on " + env + " for " + command); // NOI18N
            }

            echannel.setCommand(command);
            echannel.setXForwarding(params == null ? false : params.x11forward);
            InputStream is = echannel.getInputStream();
            InputStream es = echannel.getErrStream();
            OutputStream os = new ProtectedOutputStream(echannel, echannel.getOutputStream());
            Authentication auth = Authentication.getFor(env);
            echannel.connect(auth.getTimeout() * 1000);
            return new ChannelStreams(echannel, is, es, os);
        }

        @Override
        public String toString() {
            return command;
        }
    };

    return start(worker, env, 2);
}
 
Example 18
Source File: TCPConnection.java    From Robot-Overlord-App with GNU General Public License v2.0 4 votes vote down vote up
/** 
 * Open a connection to a device on the net.
 * The ipAddress format is a normal URI - name:password@ipaddress:port
 * @param ipAddress the network address of the device
 */
@Override
public void openConnection(String ipAddress) throws Exception {
	if (portOpened) return;

	closeConnection();

	jsch.setKnownHosts("./.ssh/known_hosts");

	if(ipAddress.startsWith("http://")) {
		ipAddress = ipAddress.substring(7);
	}

	// the string input
	URL a = new URL("http://"+ipAddress);
	String host = a.getHost();
	int port = a.getPort();
	String userInfo = a.getUserInfo();
	if(port==-1) port = DEFAULT_TCP_PORT;

	String [] userParts = userInfo.split(":");
	
	// now we have everything we need
	
	session = jsch.getSession(userParts[0], host, port);
	session.setUserInfo(new MyUserInfo());
    session.setPassword(userParts[1]);
    session.connect(30000);   // making a connection with timeout.

    channel = (ChannelExec)session.openChannel("exec");
    Log.message("Sending "+SHELL_TO_SERIAL_COMMAND);
    channel.setCommand(SHELL_TO_SERIAL_COMMAND);
    channel.connect();
    // remember the data streams
    inputStream = new BufferedReader(new InputStreamReader(channel.getInputStream()));
    outputStream = new PrintWriter(channel.getOutputStream());
    
	connectionName = ipAddress;
	portOpened = true;
	waitingForCue = true;
	keepPolling=true;

	thread = new Thread(this);
	thread.start();
}
 
Example 19
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);
    }
}