当前位置: 首页>>代码示例>>Java>>正文


Java ChannelExec.setInputStream方法代码示例

本文整理汇总了Java中com.jcraft.jsch.ChannelExec.setInputStream方法的典型用法代码示例。如果您正苦于以下问题:Java ChannelExec.setInputStream方法的具体用法?Java ChannelExec.setInputStream怎么用?Java ChannelExec.setInputStream使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.jcraft.jsch.ChannelExec的用法示例。


在下文中一共展示了ChannelExec.setInputStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: 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

示例2: 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

示例3: exec

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
@Override
public int exec() throws IOException {
    try {
        final ChannelExec channel = ChannelExec.class.cast(
            this.session.openChannel("exec")
        );
        channel.setErrStream(this.stderr, false);
        channel.setOutputStream(this.stdout, false);
        channel.setInputStream(this.stdin, false);
        channel.setCommand(this.command);
        channel.connect();
        Logger.info(this, "$ %s", this.command);
        return this.exec(channel);
    } catch (final JSchException ex) {
        throw new IOException(ex);
    } finally {
        this.session.disconnect();
    }
}
 
开发者ID:jcabi,项目名称:jcabi-ssh,代码行数:20,代码来源:Execution.java

示例4: 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

示例5: 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

示例6: exec

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
/**
 * 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 {
		channel = connect("exec", command);
		ChannelExec chexec = (ChannelExec) channel;
		chexec.setInputStream(null);
		chexec.setPty(true); // Allocate pseudo-tty (same as "ssh -t")

		// We don't need these
		//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) {
		if (debug) e.printStackTrace();
		return null;
	}
}
 
开发者ID:pcingola,项目名称:BigDataScript,代码行数:31,代码来源:Ssh.java

示例7: execute

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
/**
 *
 * @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;
}
 
开发者ID:Axway,项目名称:ats-framework,代码行数:45,代码来源:JschSshClient.java

示例8: executeCommand

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
public int executeCommand(boolean setPty, String command, CommandResultConsumer consumer) {
	Session ssh = SshUtil.getInstance().createSshSession(username, hostname);
	int resultCode = 255;

	try {
		ssh.connect();
		LOGGER.debug("Connected to ssh console");
		ChannelExec channel = (ChannelExec) ssh.openChannel("exec");
		channel.setPty(setPty);
		channel.setCommand(command);
		channel.setInputStream(null);
		channel.setOutputStream(System.err);

		LOGGER.debug("Executing command: '{}'", command);
		channel.connect();
		try {
			if (consumer != null) {
				consumer.consume(channel.getInputStream());
			}
		} catch (IOException ex) {
			throw new RuntimeException("Unable to read console output", ex);
		} finally {
			channel.disconnect();
		}
		resultCode = channel.getExitStatus();
	} catch (JSchException x) {
		LOGGER.error("Error SSH to " + username + "@" + hostname, x);
	} finally {
		ssh.disconnect();
	}

	return resultCode;
}
 
开发者ID:xtf-cz,项目名称:xtf,代码行数:34,代码来源:OpenShiftNode.java

示例9: execCmd

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
private SSHCommand execCmd(SSHCommand cmd) throws JSchException, IOException {
    Log.d("-------", "COMMAND: "+cmd.getCommand());

    ChannelExec channel = (ChannelExec) currSSHSess.openChannel("exec");
    channel.setCommand(cmd.getCommand());
    channel.setInputStream(null);

    final InputStream
            in = channel.getInputStream(),
            err = channel.getErrStream();
    channel.connect();

    final BufferedReader
            readerIn = new BufferedReader(new InputStreamReader(in)),
            readerEr = new BufferedReader(new InputStreamReader(err));

    final StringBuilder
            errStr = new StringBuilder(),
            inStr  = new StringBuilder();

    String line;

    while ((line = readerIn.readLine()) != null) {
        inStr.append(line).append('\n');
        progress(line + "\n");
    }

    while ((line = readerEr.readLine()) != null) {
        errStr.append(line).append('\n');
        progress(line + "\n");
    }

    channel.disconnect();

    cmd.setCmdOut(inStr.toString());
    cmd.setErrorOut(errStr.toString());

    return cmd;
}
 
开发者ID:konachan700,项目名称:SSHFileManager,代码行数:40,代码来源:SSHHelper.java

示例10: executeSshCommand

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
/**
 * 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());
}
 
开发者ID:gemxd,项目名称:gemfirexd-oss,代码行数:53,代码来源:RemoteLauncherCommands.java

示例11: exec

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
public void exec(String cmdToRun) throws IOException, JSchException, InterruptedException {
    ChannelExec channelExec = (ChannelExec) remoteClient.getSession().openChannel("exec");

    channelExec.setCommand(cmdToRun);
    channelExec.setInputStream(null);

    InputStream [] inputs = new InputStream [] {channelExec.getInputStream(), channelExec.getExtInputStream(), channelExec.getErrStream()};

    channelExec.connect();
    final long now = System.currentTimeMillis();
    boolean gotResult = false;
    while (!gotResult && System.currentTimeMillis() - now < 1000) {
        for (int i = 0; i < inputs.length; ++i)  {
            InputStream input = inputs[i];
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            String line;
            StringBuilder builder = new StringBuilder();
            if (reader.ready()) {
                while ((line = reader.readLine()) != null) {
                    builder.append(line).append("\n");
                }
                gotResult = true;
                System.out.println("Got reply from input#" + i + ":\n" + builder.toString());
                break;
            }
        }
        Thread.sleep(50);
    }

    int exitStatus = channelExec.getExitStatus();
    channelExec.disconnect();
    System.out.println("Executing command exit status: " + exitStatus);
}
 
开发者ID:sanchouss,项目名称:InstantPatchIdeaPlugin,代码行数:34,代码来源:RemoteProcessRunnerExec.java

示例12: sessionConnectGenerateChannel

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
/**
  * 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;

 }
 
开发者ID:eBay,项目名称:parallec,代码行数:42,代码来源:SshProvider.java

示例13: exec2

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
public InputStream exec2(String command, InputStream opt) throws JSchException, IOException {
  ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
  channel.setCommand(command);
  channel.setInputStream(opt);
  InputStream in = channel.getInputStream();
  channel.connect();
  return in;
}
 
开发者ID:gerrit-review,项目名称:gerrit,代码行数:9,代码来源:SshSession.java

示例14: readOutput

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
private void readOutput(ChannelExec channel) throws IOException, JSchException {
    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();
    while (line != null && line.length() > 0) {
        System.out.printf("%d: %s\n", count++, line);
        line = br.readLine();
    }

}
 
开发者ID:starksm64,项目名称:RaspberryPiBeaconParser,代码行数:16,代码来源:TstJSch.java

示例15: executeCommand

import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
/**
 *
 * {@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();
}
 
开发者ID:pentaho,项目名称:pentaho-kettle,代码行数:33,代码来源:SftpFileSystemWindows.java


注:本文中的com.jcraft.jsch.ChannelExec.setInputStream方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。