Search in sources :

Example 51 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project ant by apache.

the class SSHExec method executeCommand.

private void executeCommand(final Session session, final String cmd, final StringBuilder sb) throws BuildException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ByteArrayOutputStream errout = new ByteArrayOutputStream();
    final OutputStream teeErr = suppressSystemErr ? errout : new TeeOutputStream(errout, KeepAliveOutputStream.wrapSystemErr());
    final OutputStream tee = suppressSystemOut ? out : new TeeOutputStream(out, KeepAliveOutputStream.wrapSystemOut());
    InputStream istream = null;
    if (inputFile != null) {
        try {
            istream = Files.newInputStream(inputFile.toPath());
        } catch (final IOException e) {
            // because we checked the existence before, this one
            // shouldn't happen What if the file exists, but there
            // are no read permissions?
            log("Failed to read " + inputFile + " because of: " + e.getMessage(), Project.MSG_WARN);
        }
    }
    if (inputProperty != null) {
        final String inputData = getProject().getProperty(inputProperty);
        if (inputData != null) {
            istream = new ByteArrayInputStream(inputData.getBytes());
        }
    }
    if (inputString != null) {
        istream = new ByteArrayInputStream(inputString.getBytes());
    }
    if (useSystemIn) {
        istream = KeepAliveInputStream.wrapSystemIn();
    }
    try {
        final ChannelExec channel;
        session.setTimeout((int) maxwait);
        /* execute the command */
        channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(cmd);
        channel.setOutputStream(tee);
        channel.setExtOutputStream(tee);
        channel.setErrStream(teeErr);
        if (istream != null) {
            channel.setInputStream(istream);
        }
        channel.setPty(usePty);
        channel.connect();
        // wait for it to finish
        thread = new Thread() {

            @Override
            public void run() {
                while (!channel.isClosed()) {
                    if (thread == null) {
                        return;
                    }
                    try {
                        sleep(RETRY_INTERVAL);
                    } catch (final Exception e) {
                    // ignored
                    }
                }
            }
        };
        thread.start();
        thread.join(maxwait);
        if (thread.isAlive()) {
            // ran out of time
            thread = null;
            if (getFailonerror()) {
                throw new BuildException(TIMEOUT_MESSAGE);
            }
            log(TIMEOUT_MESSAGE, Project.MSG_ERR);
        } else {
            // stdout to outputFile
            if (outputFile != null) {
                writeToFile(out.toString(), append, outputFile);
            }
            // set errorProperty
            if (errorProperty != null) {
                getProject().setNewProperty(errorProperty, errout.toString());
            }
            // stderr to errorFile
            if (errorFile != null) {
                writeToFile(errout.toString(), appenderr, errorFile);
            }
            // this is the wrong test if the remote OS is OpenVMS,
            // but there doesn't seem to be a way to detect it.
            final int ec = channel.getExitStatus();
            // set resultproperty
            if (resultProperty != null) {
                getProject().setNewProperty(resultProperty, Integer.toString(ec));
            }
            if (ec != 0) {
                final String msg = "Remote command failed with exit status " + ec;
                if (getFailonerror()) {
                    throw new BuildException(msg);
                }
                log(msg, Project.MSG_ERR);
            }
        }
    } catch (final BuildException e) {
        throw e;
    } catch (final JSchException e) {
        if (e.getMessage().contains("session is down")) {
            if (getFailonerror()) {
                throw new BuildException(TIMEOUT_MESSAGE, e);
            }
            log(TIMEOUT_MESSAGE, Project.MSG_ERR);
        } else {
            if (getFailonerror()) {
                throw new BuildException(e);
            }
            log("Caught exception: " + e.getMessage(), Project.MSG_ERR);
        }
    } catch (final Exception e) {
        if (getFailonerror()) {
            throw new BuildException(e);
        }
        log("Caught exception: " + e.getMessage(), Project.MSG_ERR);
    } finally {
        sb.append(out.toString());
        FileUtils.close(istream);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) TeeOutputStream(org.apache.tools.ant.util.TeeOutputStream) KeepAliveInputStream(org.apache.tools.ant.util.KeepAliveInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeepAliveOutputStream(org.apache.tools.ant.util.KeepAliveOutputStream) TeeOutputStream(org.apache.tools.ant.util.TeeOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) JSchException(com.jcraft.jsch.JSchException) ByteArrayInputStream(java.io.ByteArrayInputStream) BuildException(org.apache.tools.ant.BuildException)

Example 52 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project ant by apache.

the class AbstractSshMessage method openExecChannel.

/**
 * Open an ssh channel.
 * @param command the command to use
 * @return the channel
 * @throws JSchException on error
 */
protected Channel openExecChannel(final String command) throws JSchException {
    final ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(command);
    return channel;
}
Also used : ChannelExec(com.jcraft.jsch.ChannelExec)

Example 53 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project incubator-gobblin by apache.

the class SftpLightWeightFileSystem method getFileStatus.

@Override
public FileStatus getFileStatus(Path path) throws IOException {
    ChannelSftp channelSftp = null;
    ChannelExec channelExec1 = null;
    ChannelExec channelExec2 = null;
    try {
        channelSftp = this.fsHelper.getSftpChannel();
        SftpATTRS sftpAttrs = channelSftp.stat(HadoopUtils.toUriPath(path));
        FsPermission permission = new FsPermission((short) sftpAttrs.getPermissions());
        channelExec1 = this.fsHelper.getExecChannel("id " + sftpAttrs.getUId());
        String userName = IOUtils.toString(channelExec1.getInputStream());
        channelExec2 = this.fsHelper.getExecChannel("id " + sftpAttrs.getGId());
        String groupName = IOUtils.toString(channelExec2.getInputStream());
        FileStatus fs = new FileStatus(sftpAttrs.getSize(), sftpAttrs.isDir(), 1, 0l, sftpAttrs.getMTime(), sftpAttrs.getATime(), permission, StringUtils.trimToEmpty(userName), StringUtils.trimToEmpty(groupName), path);
        return fs;
    } catch (SftpException e) {
        throw new IOException(e);
    } finally {
        safeDisconnect(channelSftp);
        safeDisconnect(channelExec1);
        safeDisconnect(channelExec2);
    }
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) FileStatus(org.apache.hadoop.fs.FileStatus) SftpATTRS(com.jcraft.jsch.SftpATTRS) SftpException(com.jcraft.jsch.SftpException) FsPermission(org.apache.hadoop.fs.permission.FsPermission) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 54 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project hutool by looly.

the class JschUtil method exec.

/**
 * 打开Exec连接<br>
 * 获取ChannelExec后首先
 *
 * @param session Session会话
 * @param cmd 命令
 * @param charset 发送和读取内容的编码
 * @return {@link ChannelExec}
 * @since 4.0.3
 */
public static String exec(Session session, String cmd, Charset charset) {
    if (null == charset) {
        charset = CharsetUtil.CHARSET_UTF_8;
    }
    ChannelExec channel;
    try {
        channel = (ChannelExec) session.openChannel("exec");
    } catch (JSchException e) {
        throw new JschRuntimeException(e);
    }
    channel.setCommand(StrUtil.bytes(cmd, charset));
    channel.setInputStream(null);
    channel.setErrStream(System.err);
    InputStream in = null;
    try {
        // 执行命令 等待执行结束
        channel.connect();
        in = channel.getInputStream();
        return IoUtil.read(in, CharsetUtil.CHARSET_UTF_8);
    } catch (IOException e) {
        throw new IORuntimeException(e);
    } catch (JSchException e) {
        throw new JschRuntimeException(e);
    } finally {
        IoUtil.close(in);
        close(channel);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) IORuntimeException(cn.hutool.core.io.IORuntimeException) InputStream(java.io.InputStream) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 55 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project acceptance-test-harness by jenkinsci.

the class GitRepo method transferToDockerContainer.

/**
 * Zip bare repository, copy to Docker container using sftp, then unzip.
 * The repo is now accessible over "ssh://git@ip:port/home/git/gitRepo.git"
 *
 * @param host IP of Docker container
 * @param port SSH port of Docker container
 */
public void transferToDockerContainer(String host, int port) {
    try {
        Path zipPath = Files.createTempFile("git", "zip");
        File zippedRepo = zipPath.toFile();
        String zippedFilename = zipPath.getFileName().toString();
        ZipUtil.pack(new File(dir.getPath()), zippedRepo);
        Properties props = new Properties();
        props.put("StrictHostKeyChecking", "no");
        JSch jSch = new JSch();
        jSch.addIdentity(privateKey.getAbsolutePath());
        Session session = jSch.getSession("git", host, port);
        session.setConfig(props);
        session.connect();
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        channel.cd("/home/git");
        channel.put(new FileInputStream(zippedRepo), zippedFilename);
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand("unzip " + zippedFilename + " -d " + REPO_NAME);
        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();
        channel.disconnect();
        session.disconnect();
        Files.delete(zipPath);
    } catch (IOException | JSchException | SftpException e) {
        throw new AssertionError("Can't transfer git repository to docker container", e);
    }
}
Also used : Path(java.nio.file.Path) JSchException(com.jcraft.jsch.JSchException) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SftpException(com.jcraft.jsch.SftpException) IOException(java.io.IOException) Properties(java.util.Properties) JSch(com.jcraft.jsch.JSch) FileInputStream(java.io.FileInputStream) ChannelExec(com.jcraft.jsch.ChannelExec) ChannelSftp(com.jcraft.jsch.ChannelSftp) BufferedReader(java.io.BufferedReader) File(java.io.File) Session(com.jcraft.jsch.Session)

Aggregations

ChannelExec (com.jcraft.jsch.ChannelExec)71 InputStream (java.io.InputStream)42 IOException (java.io.IOException)41 Channel (com.jcraft.jsch.Channel)33 JSchException (com.jcraft.jsch.JSchException)31 JSch (com.jcraft.jsch.JSch)25 Session (com.jcraft.jsch.Session)20 BufferedReader (java.io.BufferedReader)19 InputStreamReader (java.io.InputStreamReader)19 FileInputStream (java.io.FileInputStream)17 OutputStream (java.io.OutputStream)14 Properties (java.util.Properties)13 File (java.io.File)9 FileOutputStream (java.io.FileOutputStream)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 SftpException (com.jcraft.jsch.SftpException)6 GFacException (org.apache.airavata.gfac.core.GFacException)6 ArrayList (java.util.ArrayList)4 UserInfo (com.jcraft.jsch.UserInfo)3 SSHApiException (org.apache.airavata.gfac.core.SSHApiException)3