本文整理匯總了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);
}
}
示例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();
}
}
示例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();
}
}
示例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();
}
示例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();
}
}
}
示例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;
}
}
示例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;
}
示例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;
}
示例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;
}
示例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());
}
示例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);
}
示例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;
}
示例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;
}
示例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();
}
}
示例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();
}