本文整理汇总了Java中com.jcraft.jsch.ChannelExec.connect方法的典型用法代码示例。如果您正苦于以下问题:Java ChannelExec.connect方法的具体用法?Java ChannelExec.connect怎么用?Java ChannelExec.connect使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.jcraft.jsch.ChannelExec
的用法示例。
在下文中一共展示了ChannelExec.connect方法的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: 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());
}
}
示例6: 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();
}
}
示例7: 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();
}
示例8: 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();
}
}
示例9: scpPut
import com.jcraft.jsch.ChannelExec; //导入方法依赖的package包/类
@Override
public OutputStream scpPut(String remoteFilePath, long length, String mode) throws Throwable {
open();
if (!Pattern.matches("\\d{4}", mode)) {
throw new IllegalArgumentException("Invalid file mode: " + mode);
}
String dir = PathUtil.getParentDirectory(remoteFilePath);
String fileName = PathUtil.getFileName(remoteFilePath);
// exec 'scp -t -d remoteTargetDirectory' remotely
String command = "scp -t -d \"" + dir + "\"";
final ChannelExec channel = (ChannelExec) _jschSession.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
final InputStream in = channel.getInputStream();
channel.connect();
return new ScpOutputStream(channel, in, out, new FileInfo(mode, length, fileName));
}
示例10: 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();
}
}
示例11: 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();
}
示例12: 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);
}
}
示例13: 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();
}
}
}
示例14: 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;
}
}
示例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);
}