當前位置: 首頁>>代碼示例>>Java>>正文


Java ChannelExec.setCommand方法代碼示例

本文整理匯總了Java中com.jcraft.jsch.ChannelExec.setCommand方法的典型用法代碼示例。如果您正苦於以下問題:Java ChannelExec.setCommand方法的具體用法?Java ChannelExec.setCommand怎麽用?Java ChannelExec.setCommand使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.jcraft.jsch.ChannelExec的用法示例。


在下文中一共展示了ChannelExec.setCommand方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: execute

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
@Override
public CliProcess execute(String command)
{
    try {
        Session session = createSession();
        LOGGER.info("Executing on {}@{}:{}: {}", session.getUserName(), session.getHost(), session.getPort(), command);
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(command);
        JSchCliProcess process = new JSchCliProcess(session, channel);
        process.connect();
        return process;
    }
    catch (JSchException | IOException exception) {
        throw new RuntimeException(exception);
    }
}
 
開發者ID:prestodb,項目名稱:tempto,代碼行數:17,代碼來源:JSchSshClient.java

示例2: createTCPProxy

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
private void createTCPProxy() {
	try {
		final String cleanCommand = String.format("sudo docker ps -a | grep 'hours ago' | awk '{print $1}' | xargs --no-run-if-empty sudo docker rm",
				containerName,
				this.targetHost,
				this.targetPort,
				sourceIPs,
				ImageRegistry.get().tcpProxy());
		LOGGER.info("Establishing SSH shell");
		ssh = SshUtil.getInstance()
				.createSshSession(TestConfiguration.proxyHostUsername(), getProxyHost());
		ssh.connect();
		LOGGER.debug("Connected to ssh console");

		final ChannelExec cleanChannel = (ChannelExec) ssh.openChannel("exec");
		cleanChannel.setPty(true);
		cleanChannel.setCommand(cleanCommand);
		cleanChannel.setInputStream(null);
		cleanChannel.setOutputStream(System.err);

		LOGGER.debug("Executing command: '{}'", cleanCommand);
		cleanChannel.connect();
		cleanChannel.disconnect();

		final String command = String.format("sudo docker run -it --name %s --net=host --rm -e AB_OFF=true -e TARGET_HOST=%s -e TARGET_PORT=%s -e TARGET_VIA=%s %s",
				containerName,
				this.targetHost,
				this.targetPort,
				sourceIPs,
				ImageRegistry.get().tcpProxy());
		LOGGER.info("Establishing SSH shell");
		ssh = SshUtil.getInstance()
				.createSshSession(TestConfiguration.proxyHostUsername(), getProxyHost());
		ssh.connect();
		LOGGER.debug("Connected to ssh console");

		final ChannelExec channel = (ChannelExec) ssh.openChannel("exec");
		channel.setPty(true);
		channel.setCommand(command);
		channel.setInputStream(null);
		channel.setOutputStream(System.err);

		LOGGER.debug("Executing command: '{}'", command);
		channel.connect();
		final LineIterator li = IOUtils.lineIterator(new InputStreamReader(channel.getInputStream()));
		final Pattern portLine = Pattern.compile(".*Listening on port ([0-9]*).*$");
		listenPort = 0;
		while (li.hasNext()) {
			final String line = li.next();
			LOGGER.trace("Shell line: {}", line);
			final Matcher m = portLine.matcher(line);
			if (m.matches()) {
				listenPort = Integer.parseInt(m.group(1));
				LOGGER.info("Connection listening on port {}", listenPort);
				break;
			}
		}
		channel.disconnect();
	} catch (final JSchException | IOException e) {
		LOGGER.debug("Error in creating SSH connection to proxy host", e);
		throw new IllegalStateException("Cannot open SSH connection", e);
	}
}
 
開發者ID:xtf-cz,項目名稱:xtf,代碼行數:64,代碼來源:ProxiedConnectionManager.java

示例3: executeSSH

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
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;
}
 
開發者ID:rajeshrv,項目名稱:SpringMicroservice,代碼行數:41,代碼來源:DeploymentEngine.java

示例4: executeCommand

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
/**
 * Convenience method to execute a command on the given remote session, using the given string
 * as part of the error if it fails to run.
 *
 * @param roboRioSession The ssh session of the roboRio
 * @param command        The command to execute
 * @param errorString    The error string to put in the exception if an error occurs. The return
 *                       code will be appended to the end
 * @throws JSchException If an ssh error occurs
 * @throws IOException   Thrown if there is an io error, or if the command fails to run
 */
private void executeCommand(Session roboRioSession, String command, String errorString) throws JSchException, IOException {
    // Extract the JRE
    m_logger.debug("Running command " + command);
    ChannelExec channel = (ChannelExec) roboRioSession.openChannel(EXEC_COMMAND);
    channel.setCommand(command);
    channel.connect();
    int sleepCount = 0;
    // Sleep for up to 10 seconds while we wait for the command to execute, checking every 100 milliseconds
    do {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            m_logger.warn("Interrupted exception while waiting for command " + command + " to finish", e);
        }
    } while (!channel.isClosed() && sleepCount++ < 100);

    int res = channel.getExitStatus();
    if (res != SUCCESS) {
        m_logger.debug("Error with command " + command);
        throw new IOException(errorString + " " + res);
    }
    channel.disconnect();
}
 
開發者ID:wpilibsuite,項目名稱:java-installer,代碼行數:35,代碼來源:DeployController.java

示例5: forceCreateDirectories

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
/**
 * 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());
    }
}
 
開發者ID:asebak,項目名稱:embeddedlinux-jvmdebugger-intellij,代碼行數:30,代碼來源:SSHHandlerTarget.java

示例6: runJavaApp

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
/**
 * 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());
    }
}
 
開發者ID:asebak,項目名稱:embeddedlinux-jvmdebugger-intellij,代碼行數:32,代碼來源:SSHHandlerTarget.java

示例7: upload

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
@Override
public void upload(Path file, String remotePath)
{
    Session session = null;
    try {
        session = createSession();
        LOGGER.info("Uploading {} onto {}@{}:{}:{}", file, session.getUserName(), session.getHost(), session.getPort(), remotePath);
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        String command = "scp -t " + remotePath;
        channel.setCommand(command);

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

        sendSCPFile(file, channel, in, out);
    }
    catch (JSchException | IOException exception) {
        Throwables.propagate(exception);
    }
    finally {
        if (session != null) { session.disconnect(); }
    }
}
 
開發者ID:prestodb,項目名稱:tempto,代碼行數:24,代碼來源:JSchSshClient.java

示例8: testExec

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
@Test(timeout = 5000)
public void testExec(TestContext context) throws Exception {
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  ChannelExec channel = (ChannelExec) session.openChannel("exec");
  channel.setCommand("the-command arg1 arg2");
  channel.connect();
  InputStream in = channel.getInputStream();
  StringBuilder input = new StringBuilder();
  while (!input.toString().equals("the_output")) {
    int a = in.read();
    if (a == -1) {
      break;
    }
    input.append((char)a);
  }
  OutputStream out = channel.getOutputStream();
  out.write("the_input".getBytes());
  out.flush();
  while (channel.isConnected()) {
    Thread.sleep(1);
  }
  assertEquals(2, channel.getExitStatus());
  session.disconnect();
}
 
開發者ID:vert-x3,項目名稱:vertx-shell,代碼行數:27,代碼來源:SSHTestBase.java

示例9: exec

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
@SuppressWarnings("resource")
public String exec(String command, InputStream opt) throws JSchException, IOException {
  ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
  try {
    channel.setCommand(command);
    channel.setInputStream(opt);
    InputStream in = channel.getInputStream();
    InputStream err = channel.getErrStream();
    channel.connect();

    Scanner s = new Scanner(err).useDelimiter("\\A");
    error = s.hasNext() ? s.next() : null;

    s = new Scanner(in).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
  } finally {
    channel.disconnect();
  }
}
 
開發者ID:gerrit-review,項目名稱:gerrit,代碼行數:20,代碼來源:SshSession.java

示例10: executeCommand

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
private void executeCommand(Session session,CommandInfo commandInfo, CommandOutput commandOutput) throws GFacException {
        String command = commandInfo.getCommand();
        ChannelExec channelExec = null;
        try {
            if (!session.isConnected()) {
//                session = getOpenSession();
                log.error("Error! client session is closed");
                throw new JSchException("Error! client session is closed");
            }
            channelExec = ((ChannelExec) session.openChannel("exec"));
            channelExec.setCommand(command);
            channelExec.setInputStream(null);
            channelExec.setErrStream(commandOutput.getStandardError());
            log.info("Executing command {}", commandInfo.getCommand());
            channelExec.connect();
            commandOutput.onOutput(channelExec);
        } catch (JSchException e) {
            throw new GFacException("Unable to execute command - ", e);
        }finally {
            //Only disconnecting the channel, session can be reused
            if (channelExec != null) {
                commandOutput.exitCode(channelExec.getExitStatus());
                channelExec.disconnect();
            }
        }
    }
 
開發者ID:apache,項目名稱:airavata,代碼行數:27,代碼來源:ArchiveTask.java

示例11: get

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:apache,項目名稱:ant-ivy,代碼行數:36,代碼來源:Scp.java

示例12: getFileinfo

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:apache,項目名稱:ant-ivy,代碼行數:36,代碼來源:Scp.java

示例13: execCommand

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
private static String execCommand(Session session, TextStream out, String command) throws JSchException, IOException {
    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(command);
    channel.setInputStream(null);
    channel.setErrStream(System.err);

    InputStream in = channel.getInputStream();
    channel.connect();
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    int count = 0;
    String line = br.readLine();
    StringWriter sw = new StringWriter();
    while (line != null) {
        String info = String.format("%d: %s\n", count++, line);
        sw.append(info);
        out.appendText(info);
        line = br.readLine();
    }
    session.disconnect();
    return sw.toString();
}
 
開發者ID:starksm64,項目名稱:RaspberryPiBeaconParser,代碼行數:22,代碼來源:JSchUtils.java

示例14: executeCommandChannel

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:sonyxperiadev,項目名稱:gerrit-events,代碼行數:31,代碼來源:SshConnectionImpl.java

示例15: startCommand

import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
/**
 * 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);
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:43,代碼來源:JschSupport.java


注:本文中的com.jcraft.jsch.ChannelExec.setCommand方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。