Search in sources :

Example 11 with Channel

use of com.jcraft.jsch.Channel in project fabric8 by jboss-fuse.

the class SshContainerProvider method uploadTo.

protected void uploadTo(Session session, URL url, String path) {
    Channel channel = null;
    try (InputStream is = url.openStream()) {
        channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        final CountDownLatch uploadLatch = new CountDownLatch(1);
        sftpChannel.put(is, path, new SftpProgressMonitor() {

            @Override
            public void init(int op, String src, String dest, long max) {
            }

            @Override
            public boolean count(long count) {
                try {
                    return is.available() > 0;
                } catch (IOException e) {
                    return false;
                }
            }

            @Override
            public void end() {
                uploadLatch.countDown();
            }
        }, ChannelSftp.OVERWRITE);
        uploadLatch.await(10, TimeUnit.MINUTES);
    } catch (Exception e) {
        LOGGER.warn("Failed to upload. Will attempt downloading distribution via maven.");
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) SftpProgressMonitor(com.jcraft.jsch.SftpProgressMonitor) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException)

Example 12 with Channel

use of com.jcraft.jsch.Channel in project arduino-eclipse-plugin by Sloeber.

the class SSH method execSyncCommand.

@SuppressWarnings("resource")
public boolean execSyncCommand(String command, MessageConsoleStream stdoutConsumer, MessageConsoleStream stderrConsumer) throws JSchException, IOException {
    InputStream stdout = null;
    InputStream stderr = null;
    Channel channel = null;
    try {
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        stdout = channel.getInputStream();
        stderr = ((ChannelExec) channel).getErrStream();
        channel.connect();
        int exitCode = consumeOutputSyncAndReturnExitCode(channel);
        return exitCode == 0;
    } finally {
        try {
            if (stdout != null) {
                stdout.close();
            }
            if (stderr != null) {
                stderr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (channel != null) {
            channel.disconnect();
        }
    }
}
Also used : InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 13 with Channel

use of com.jcraft.jsch.Channel in project airavata by apache.

the class SSHUtils method listDirectory.

public static List<String> listDirectory(String path, Session session) throws IOException, JSchException, GFacException {
    // exec 'scp -t rfile' remotely
    String command = "ls " + path;
    Channel channel = session.openChannel("exec");
    StandardOutReader stdOutReader = new StandardOutReader();
    ((ChannelExec) channel).setCommand(command);
    ((ChannelExec) channel).setErrStream(stdOutReader.getStandardError());
    try {
        channel.connect();
    } catch (JSchException e) {
        channel.disconnect();
        throw new GFacException("Unable to retrieve command output. Command - " + command + " on server - " + session.getHost() + ":" + session.getPort() + " connecting user name - " + session.getUserName(), e);
    }
    stdOutReader.onOutput(channel);
    stdOutReader.getStdOutputString();
    if (stdOutReader.getStdErrorString().contains("ls:")) {
        throw new GFacException(stdOutReader.getStdErrorString());
    }
    channel.disconnect();
    return Arrays.asList(stdOutReader.getStdOutputString().split("\n"));
}
Also used : JSchException(com.jcraft.jsch.JSchException) GFacException(org.apache.airavata.gfac.core.GFacException) Channel(com.jcraft.jsch.Channel) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 14 with Channel

use of com.jcraft.jsch.Channel in project airavata by apache.

the class SSHUtils method scpThirdParty.

/**
 * This method will copy a remote file to a local directory
 *
 * @param sourceFile remote file path, this has to be a full qualified path
 * @param sourceSession JSch session for source
 * @param destinationFile This is the local file to copy, this can be a directory too
 * @param destinationSession JSch Session for target
 * @return returns the final local file path of the new file came from the remote resource
 */
public static void scpThirdParty(String sourceFile, Session sourceSession, String destinationFile, Session destinationSession, boolean ignoreEmptyFile) throws IOException, JSchException {
    OutputStream sout = null;
    InputStream sin = null;
    OutputStream dout = null;
    InputStream din = null;
    try {
        String prefix = null;
        // exec 'scp -f sourceFile'
        String sourceCommand = "scp -f " + sourceFile;
        Channel sourceChannel = sourceSession.openChannel("exec");
        ((ChannelExec) sourceChannel).setCommand(sourceCommand);
        StandardOutReader sourceStdOutReader = new StandardOutReader();
        ((ChannelExec) sourceChannel).setErrStream(sourceStdOutReader.getStandardError());
        // get I/O streams for remote scp
        sout = sourceChannel.getOutputStream();
        sin = sourceChannel.getInputStream();
        sourceChannel.connect();
        boolean ptimestamp = true;
        // exec 'scp -t destinationFile'
        String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + destinationFile;
        Channel targetChannel = destinationSession.openChannel("exec");
        StandardOutReader targetStdOutReader = new StandardOutReader();
        ((ChannelExec) targetChannel).setErrStream(targetStdOutReader.getStandardError());
        ((ChannelExec) targetChannel).setCommand(command);
        // get I/O streams for remote scp
        dout = targetChannel.getOutputStream();
        din = targetChannel.getInputStream();
        targetChannel.connect();
        if (checkAck(din) != 0) {
            String error = "Error Reading input Stream";
            log.error(error);
            throw new Exception(error);
        }
        byte[] buf = new byte[1024];
        // send '\0'
        buf[0] = 0;
        sout.write(buf, 0, 1);
        sout.flush();
        log.info("Initiating transfer from:" + sourceFile + " To: " + destinationFile + ", Ignore Empty file : " + ignoreEmptyFile);
        while (true) {
            int c = checkAck(sin);
            if (c != 'C') {
                break;
            }
            // read '0644 '
            sin.read(buf, 0, 5);
            long fileSize = 0L;
            while (true) {
                if (sin.read(buf, 0, 1) < 0) {
                    // error
                    break;
                }
                if (buf[0] == ' ')
                    break;
                fileSize = fileSize * 10L + (long) (buf[0] - '0');
            }
            String fileName = null;
            for (int i = 0; ; i++) {
                sin.read(buf, i, 1);
                if (buf[i] == (byte) 0x0a) {
                    fileName = new String(buf, 0, i);
                    break;
                }
            }
            // FIXME: Remove me after fixing file transfer issue
            if (fileSize == 0L) {
                log.warn("*****Zero byte file*****. Transferring from:" + sourceFile + " To: " + destinationFile + ", File Size : " + fileSize + ", Ignore Empty file : " + ignoreEmptyFile);
            } else {
                log.info("Transferring from:" + sourceFile + " To: " + destinationFile + ", File Size : " + fileSize + ", Ignore Empty file : " + ignoreEmptyFile);
            }
            if (fileSize == 0L && !ignoreEmptyFile) {
                String error = "Input file is empty...";
                log.error(error);
                throw new JSchException(error);
            }
            String initData = "C0644 " + fileSize + " " + fileName + "\n";
            assert dout != null;
            dout.write(initData.getBytes());
            dout.flush();
            // send '\0' to source
            buf[0] = 0;
            sout.write(buf, 0, 1);
            sout.flush();
            int rLength;
            while (true) {
                if (buf.length < fileSize)
                    rLength = buf.length;
                else
                    rLength = (int) fileSize;
                // read content of the source File
                rLength = sin.read(buf, 0, rLength);
                if (rLength < 0) {
                    // error
                    break;
                }
                // write to destination file
                dout.write(buf, 0, rLength);
                fileSize -= rLength;
                if (fileSize == 0L)
                    break;
            }
            // send '\0' to target
            buf[0] = 0;
            dout.write(buf, 0, 1);
            dout.flush();
            if (checkAck(din) != 0) {
                String error = "Error Reading input Stream";
                log.error(error);
                throw new Exception(error);
            }
            dout.close();
            dout = null;
            if (checkAck(sin) != 0) {
                String error = "Error transfering the file content";
                log.error(error);
                throw new Exception(error);
            }
            // send '\0'
            buf[0] = 0;
            sout.write(buf, 0, 1);
            sout.flush();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new JSchException(e.getMessage());
    } finally {
        try {
            if (dout != null)
                dout.close();
        } catch (Exception ee) {
            log.error("", ee);
        }
        try {
            if (din != null)
                din.close();
        } catch (Exception ee) {
            log.error("", ee);
        }
        try {
            if (sout != null)
                sout.close();
        } catch (Exception ee) {
            log.error("", ee);
        }
        try {
            if (din != null)
                din.close();
        } catch (Exception ee) {
            log.error("", ee);
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Channel(com.jcraft.jsch.Channel) ChannelExec(com.jcraft.jsch.ChannelExec) GFacException(org.apache.airavata.gfac.core.GFacException) SSHApiException(org.apache.airavata.gfac.core.SSHApiException) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException)

Example 15 with Channel

use of com.jcraft.jsch.Channel in project airavata by apache.

the class SSHUtils method scpFrom.

/**
 * This method will copy a remote file to a local directory
 *
 * @param remoteFile remote file path, this has to be a full qualified path
 * @param localFile  This is the local file to copy, this can be a directory too
 * @return returns the final local file path of the new file came from the remote resource
 */
public static void scpFrom(String remoteFile, String localFile, Session session) throws IOException, JSchException, SSHApiException {
    FileOutputStream fos = null;
    try {
        String prefix = null;
        if (new File(localFile).isDirectory()) {
            prefix = localFile + File.separator;
        }
        // exec 'scp -f remotefile' remotely
        String command = "scp -f " + remoteFile;
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        StandardOutReader stdOutReader = new StandardOutReader();
        ((ChannelExec) channel).setErrStream(stdOutReader.getStandardError());
        // get I/O streams for remote scp
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();
        if (!channel.isClosed()) {
            channel.connect();
        }
        byte[] buf = new byte[1024];
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        while (true) {
            int c = checkAck(in);
            if (c != 'C') {
                break;
            }
            // read '0644 '
            in.read(buf, 0, 5);
            long filesize = 0L;
            while (true) {
                if (in.read(buf, 0, 1) < 0) {
                    // error
                    break;
                }
                if (buf[0] == ' ')
                    break;
                filesize = filesize * 10L + (long) (buf[0] - '0');
            }
            String file = null;
            for (int i = 0; ; i++) {
                in.read(buf, i, 1);
                if (buf[i] == (byte) 0x0a) {
                    file = new String(buf, 0, i);
                    break;
                }
            }
            // System.out.println("filesize="+filesize+", file="+file);
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
            // read a content of lfile
            fos = new FileOutputStream(prefix == null ? localFile : prefix + file);
            int foo;
            while (true) {
                if (buf.length < filesize)
                    foo = buf.length;
                else
                    foo = (int) filesize;
                foo = in.read(buf, 0, foo);
                if (foo < 0) {
                    // error
                    break;
                }
                fos.write(buf, 0, foo);
                filesize -= foo;
                if (filesize == 0L)
                    break;
            }
            fos.close();
            fos = null;
            if (checkAck(in) != 0) {
                String error = "Error transfering the file content";
                log.error(error);
                throw new SSHApiException(error);
            }
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
        }
        stdOutReader.onOutput(channel);
        if (stdOutReader.getStdErrorString().contains("scp:")) {
            throw new SSHApiException(stdOutReader.getStdErrorString());
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (Exception ee) {
        }
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) SSHApiException(org.apache.airavata.gfac.core.SSHApiException) ChannelExec(com.jcraft.jsch.ChannelExec) GFacException(org.apache.airavata.gfac.core.GFacException) SSHApiException(org.apache.airavata.gfac.core.SSHApiException) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Aggregations

Channel (com.jcraft.jsch.Channel)63 InputStream (java.io.InputStream)38 ChannelExec (com.jcraft.jsch.ChannelExec)33 IOException (java.io.IOException)33 JSch (com.jcraft.jsch.JSch)32 JSchException (com.jcraft.jsch.JSchException)30 Session (com.jcraft.jsch.Session)27 FileInputStream (java.io.FileInputStream)19 ChannelSftp (com.jcraft.jsch.ChannelSftp)18 OutputStream (java.io.OutputStream)17 BufferedReader (java.io.BufferedReader)15 File (java.io.File)13 InputStreamReader (java.io.InputStreamReader)13 Properties (java.util.Properties)13 SftpException (com.jcraft.jsch.SftpException)12 FileOutputStream (java.io.FileOutputStream)10 UserInfo (com.jcraft.jsch.UserInfo)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 GFacException (org.apache.airavata.gfac.core.GFacException)4 SSHApiException (org.apache.airavata.gfac.core.SSHApiException)3