本文整理匯總了Java中com.jcraft.jsch.ChannelExec.disconnect方法的典型用法代碼示例。如果您正苦於以下問題:Java ChannelExec.disconnect方法的具體用法?Java ChannelExec.disconnect怎麽用?Java ChannelExec.disconnect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.jcraft.jsch.ChannelExec
的用法示例。
在下文中一共展示了ChannelExec.disconnect方法的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: 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;
}
示例3: 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();
}
示例4: 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());
}
}
示例5: sendSCPFile
import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
private void sendSCPFile(Path file, ChannelExec channel, InputStream in, OutputStream out)
throws IOException, JSchException
{
channel.connect();
try {
checkAck(channel, in);
sendSCPHandshake(file, out);
checkAck(channel, in);
try (InputStream fileStream = newInputStream(file)) {
ByteStreams.copy(fileStream, out);
}
out.write(0);
out.flush();
checkAck(channel, in);
}
finally {
channel.disconnect();
}
}
示例6: 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();
}
}
示例7: 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);
}
}
示例8: 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;
}
示例9: exec
import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
protected String exec(String command) {
final ChannelExec channel = openChannel(command);
final String res;
try {
final InputStream in = getInputStream(channel);
connect(channel);
res = readOutput(command, channel, in);
} finally {
try {
if (channel.isConnected()) channel.disconnect();
} catch (Exception e) {
log.warn("failed to disconnect channel", e);
}
}
return res;
}
示例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();
}
}
}
示例11: cleanup
import com.jcraft.jsch.ChannelExec; //導入方法依賴的package包/類
private static void cleanup(ChannelExec exec) {
if (exec != null) {
try {
exec.disconnect();
} catch (Throwable t) {
LOG.warn("Couldn't disconnect ssh channel", t);
}
}
}
示例12: 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;
}
示例13: 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;
}
示例14: 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;
}
}
示例15: 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;
}