本文整理汇总了Java中com.jcraft.jsch.ChannelExec.getExitStatus方法的典型用法代码示例。如果您正苦于以下问题:Java ChannelExec.getExitStatus方法的具体用法?Java ChannelExec.getExitStatus怎么用?Java ChannelExec.getExitStatus使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.jcraft.jsch.ChannelExec
的用法示例。
在下文中一共展示了ChannelExec.getExitStatus方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: 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();
}
示例2: 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;
}
示例3: getExecRemoteCommandReturnInfo
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
/**
* Reads std and error remote output which are then wrapped inside {@link RemoteCommandReturnInfo}
*
* @param channelExec the channel where the command is sent for execution
* @param timeout the length of time in ms in which the method waits for a available byte(s) as a result of command
* @return {@link RemoteCommandReturnInfo}
*/
private RemoteCommandReturnInfo getExecRemoteCommandReturnInfo(final ChannelExec channelExec, final long timeout)
throws IOException, JSchException {
final String output = scrubberService.scrub(readExecRemoteOutput(channelExec, timeout));
LOGGER.debug("remote output = {}", output);
String errorOutput = null;
// wait for the channel to close before checking the exit status
final long startTime = System.currentTimeMillis();
while (!channelExec.isClosed()) {
if ((System.currentTimeMillis() - startTime) > CHANNEL_EXEC_CLOSE_TIMEOUT) {
errorOutput = MessageFormat.format("Wait for channel to close timeout! Timeout = {0} ms",
CHANNEL_EXEC_CLOSE_TIMEOUT);
LOGGER.error(errorOutput);
break;
}
}
LOGGER.debug("Channel exec exit status = {}", channelExec.getExitStatus());
if (channelExec.getExitStatus() != 0 && channelExec.getExitStatus() != -1) {
errorOutput = readExecRemoteOutput(channelExec, timeout);
LOGGER.debug("remote error output = {}", errorOutput);
}
return new RemoteCommandReturnInfo(channelExec.getExitStatus(), output, errorOutput);
}
示例4: 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;
}
示例5: executeCmd
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
public StringPair executeCmd(String USERNAME,String PASSWORD,String host,String command)
{
StringPair result = new StringPair();
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(USERNAME, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(PASSWORD);
session.connect();
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//while((line = reader.readLine()) != null)
result.hostName = reader.readLine();
result.ip=reader.readLine();
reader.close();
int exitStatus = channelExec.getExitStatus();
channelExec.disconnect();
session.disconnect();
if(exitStatus < 0){
System.out.println("Done, but exit status not set!");
}
else if(exitStatus > 0){
System.out.println("Done, but with error!");
}
else{
System.out.println("Done!");
}
return result;
}
catch(Exception e)
{
System.err.println("Error: " + e);
return result;
}
}
示例6: run
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
@Override
public void run() {
TaskStage stage = TaskStage.FINISHED;
Map<String, String> commandResponse = new HashMap<>();
Session session = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(this.auth.userEmail, this.state.host,
this.state.port);
jsch.addIdentity("KeyPair",
EncryptionUtils.decrypt(this.auth.privateKey).getBytes(), null, null);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
for (String cmd : this.state.commands) {
// Create a channel for each command.
ChannelExec channel = (ChannelExec) session
.openChannel("exec");
channel.setCommand(cmd);
ByteArrayOutputStream out = new ByteArrayOutputStream();
channel.setOutputStream(out);
channel.setErrStream(out);
channel.connect();
while (!channel.isClosed()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
// add command output/err to response map.
commandResponse.put(cmd, out.toString());
int exitStatus = channel.getExitStatus();
channel.disconnect();
if (exitStatus != 0) {
// last command failed, sendSelfPatch the task.
stage = TaskStage.FAILED;
break;
}
}
// patch task state
sendSelfPatch(this.state, stage, commandResponse, null);
} catch (Throwable t) {
fail(this.state, t);
return;
} finally {
if (session != null) {
session.disconnect();
}
}
}
示例7: 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);
}
示例8: execute
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
public int execute(String[] commands, OutputStream stdout, OutputStream stderr) {
try {
ChannelExec ch = (ChannelExec) getSession().openChannel(CHANNEL_EXEC);
String command = buildCommand(commands);
ch.setCommand(command);
try {
InputStream out = ch.getInputStream();
InputStream err = ch.getErrStream();
ch.connect();
if (stdout != null) {
ByteStreams.copy(out, stdout);
}
if (stderr != null) {
ByteStreams.copy(err, stderr);
}
int exitCode;
while ((exitCode = ch.getExitStatus()) == -1) {
Thread.sleep(100);
}
return exitCode;
} finally {
ch.disconnect();
}
} catch (Exception e) {
throw new SshException(e);
}
}
示例9: list
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
public List<String> list(String parent) throws IOException {
Message.debug("SShRepository:list called: " + parent);
List<String> result = new ArrayList<>();
Session session = null;
ChannelExec channel = null;
session = getSession(parent);
channel = getExecChannel(session);
URI parentUri = null;
try {
parentUri = new URI(parent);
} catch (URISyntaxException e) {
throw new IOException("The uri '" + parent + "' is not valid!", e);
}
String fullCmd = replaceArgument(listCommand, parentUri.getPath());
channel.setCommand(fullCmd);
StringBuilder stdOut = new StringBuilder();
StringBuilder stdErr = new StringBuilder();
readSessionOutput(channel, stdOut, stdErr);
if (channel.getExitStatus() != 0) {
Message.error("Ssh ListCommand exited with status != 0");
Message.error(stdErr.toString());
return null;
} else {
BufferedReader br = new BufferedReader(new StringReader(stdOut.toString()));
String line = null;
while ((line = br.readLine()) != null) {
result.add(line);
}
}
return result;
}
示例10: checkExistence
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
/**
* check for existence of file or dir on target system
*
* @param filePath
* to the object to check
* @param session
* to use
* @return true: object exists, false otherwise
*/
private boolean checkExistence(String filePath, Session session) throws IOException {
Message.debug("SShRepository: checkExistence called: " + filePath);
ChannelExec channel = null;
channel = getExecChannel(session);
String fullCmd = replaceArgument(existCommand, filePath);
channel.setCommand(fullCmd);
StringBuilder stdOut = new StringBuilder();
StringBuilder stdErr = new StringBuilder();
readSessionOutput(channel, stdOut, stdErr);
return channel.getExitStatus() == 0;
}
示例11: create
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
@Override
public ExecutableChannel create() throws Exception
{
// http://stackoverflow.com/questions/6265278/whats-the-exact-differences-between-jsch-channelexec-and-channelshell
this.session = acquire(SshConnection.builder().from(JschSshClient.this.connection).sessionTimeout(0).build());
executor = (ChannelExec) session.openChannel("exec");
executor.setCommand(command);
executor.setErrStream(new ByteArrayOutputStream());
InputStream inputStream = executor.getInputStream();
InputStream errStream = executor.getErrStream();
OutputStream outStream = executor.getOutputStream();
executor.connect();
return new ExecutableChannel(outStream, inputStream, errStream, new Supplier<Integer>()
{
@Override
public Integer get()
{
int exitStatus = executor.getExitStatus();
return exitStatus != -1 ? exitStatus : null;
}
}, new Closeable()
{
@Override
public void close() throws IOException
{
clear();
}
});
}
示例12: 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();
}
示例13: executeAndGenResponse
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
/**
* Seems there are bad naming in the library the sysout is in
* channel.getInputStream(); the syserr is in
* ((ChannelExec)channel).setErrStream(os);
*
* @param channel
* the channel
* @return the response on singe request
*/
public ResponseOnSingeRequest executeAndGenResponse(ChannelExec channel) {
ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest();
InputStream in = null;
OutputStream outputStreamStdErr = new ByteArrayOutputStream();
StringBuilder sbStdOut = new StringBuilder();
try {
in = channel.getInputStream();
channel.setErrStream(outputStreamStdErr);
byte[] tmp = new byte[ParallecGlobalConfig.sshBufferSize];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, ParallecGlobalConfig.sshBufferSize);
if (i < 0)
break;
sbStdOut.append(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (in.available() > 0)
continue;
sshResponse.setFailObtainResponse(false);
// exit 0 is good
int exitStatus = channel.getExitStatus();
sshResponse.setStatusCodeInt(exitStatus);
sshResponse.setStatusCode(Integer.toString(exitStatus));
break;
}
Thread.sleep(ParallecGlobalConfig.sshSleepMIllisBtwReadBuffer);
}
sshResponse.setResponseBody(sbStdOut.toString());
sshResponse.setErrorMessage(outputStreamStdErr.toString());
sshResponse.setReceiveTimeNow();
} catch (Exception t) {
throw new RuntimeException(t);
}
return sshResponse;
}
示例14: waitForChannelClosed
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
@Override
protected boolean waitForChannelClosed(ChannelExec channel, InputStream stdout, InputStream stderr) {
boolean success = true;
try {
byte[] tmp = new byte[1024];
while (true) {
while (stdout.available() > 0) {
int i = stdout.read(tmp, 0, 1024);
if (i < 0) {
break;
}
}
if (channel.isClosed()) {
if (stdout.available() > 0) {
continue;
}
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
// ignore
}
}
if (channel.getExitStatus() != 0) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(stderr));
logger.error(String.format("exit-status: %d - %s", channel.getExitStatus(), read(reader)));
} finally {
if (reader != null) {
reader.close();
}
}
success = false;
}
} catch (IOException e) {
logger.error(e.getMessage().replace("\n", " "));
}
return success;
}