Search in sources :

Example 1 with JSch

use of com.jcraft.jsch.JSch in project voltdb by VoltDB.

the class ExportOnServerVerifier method verifySetup.

boolean verifySetup(String[] args) throws Exception {
    String[] remoteHosts = args[0].split(",");
    final String homeDir = System.getProperty("user.home");
    final String sshDir = homeDir + File.separator + ".ssh";
    final String sshConfigPath = sshDir + File.separator + "config";
    //Oh yes...
    loadAllPrivateKeys(new File(sshDir));
    OpenSshConfig sshConfig = null;
    if (new File(sshConfigPath).exists()) {
        sshConfig = new OpenSshConfig(new File(sshConfigPath));
    }
    final String defaultKnownHosts = sshDir + "/known_hosts";
    if (new File(defaultKnownHosts).exists()) {
        m_jsch.setKnownHosts(defaultKnownHosts);
    }
    for (String hostString : remoteHosts) {
        String[] split = hostString.split(":");
        String host = split[0];
        RemoteHost rh = new RemoteHost();
        rh.path = split[1];
        String user = System.getProperty("user.name");
        int port = 22;
        File identityFile = null;
        String configHost = host;
        if (sshConfig != null) {
            OpenSshConfig.Host hostConfig = sshConfig.lookup(host);
            if (hostConfig.getUser() != null) {
                user = hostConfig.getUser();
            }
            if (hostConfig.getPort() != -1) {
                port = hostConfig.getPort();
            }
            if (hostConfig.getIdentityFile() != null) {
                identityFile = hostConfig.getIdentityFile();
            }
            if (hostConfig.getHostName() != null) {
                configHost = hostConfig.getHostName();
            }
        }
        Session session = null;
        if (identityFile != null) {
            JSch jsch = new JSch();
            jsch.addIdentity(identityFile.getAbsolutePath());
            session = jsch.getSession(user, configHost, port);
        } else {
            session = m_jsch.getSession(user, configHost, port);
        }
        rh.session = session;
        session.setConfig("StrictHostKeyChecking", "no");
        session.setDaemonThread(true);
        session.connect();
        final ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        rh.channel = channel;
        channel.connect();
        touchActiveTracker(rh);
        m_hosts.add(rh);
    }
    m_partitions = Integer.parseInt(args[1]);
    for (int i = 0; i < m_partitions; i++) {
        m_rowTxnIds.put(i, new TreeMap<Long, Long>());
        m_maxPartTxId.put(i, Long.MIN_VALUE);
        m_checkedUpTo.put(i, 0);
        m_readUpTo.put(i, new AtomicLong(0));
    }
    m_clientPath = new File(args[2]);
    if (!m_clientPath.exists() || !m_clientPath.isDirectory()) {
        if (!m_clientPath.mkdir()) {
            throw new IOException("Issue with transaction ID path");
        }
    }
    for (RemoteHost rh : m_hosts) {
        boolean existsOrIsDir = true;
        try {
            SftpATTRS stat = rh.channel.stat(rh.path);
            if (!stat.isDir()) {
                existsOrIsDir = false;
            }
        } catch (SftpException e) {
            if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
                existsOrIsDir = false;
            } else {
                Throwables.propagate(e);
            }
        }
        if (!existsOrIsDir) {
            rh.channel.mkdir(rh.path);
        }
    }
    boolean skinny = false;
    if (args.length > 3 && args[3] != null && !args[3].trim().isEmpty()) {
        skinny = Boolean.parseBoolean(args[3].trim().toLowerCase());
    }
    return skinny;
}
Also used : SftpATTRS(com.jcraft.jsch.SftpATTRS) SftpException(com.jcraft.jsch.SftpException) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) ChannelSftp(com.jcraft.jsch.ChannelSftp) AtomicLong(java.util.concurrent.atomic.AtomicLong) OpenSshConfig(org.spearce_voltpatches.jgit.transport.OpenSshConfig) AtomicLong(java.util.concurrent.atomic.AtomicLong) File(java.io.File) Session(com.jcraft.jsch.Session)

Example 2 with JSch

use of com.jcraft.jsch.JSch in project voltdb by VoltDB.

the class SSHTools method cmdSSH.

/*
     * The code from here to the end of the file is code that integrates with an external
     * SSH library (JSCH, http://www.jcraft.com/jsch/).  If you wish to replaces this
     * library, these are the methods that need to be re-worked.
     */
public String cmdSSH(String user, String password, String key, String host, String command) {
    StringBuilder result = new StringBuilder(2048);
    try {
        JSch jsch = new JSch();
        // Set the private key
        if (null != key)
            jsch.addIdentity(key);
        Session session = jsch.getSession(user, host, 22);
        session.setTimeout(5000);
        // To avoid the UnknownHostKey issue
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        if (password != null && !password.trim().isEmpty()) {
            session.setPassword(password);
        }
        session.connect();
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        // Direct stderr output of command
        InputStream err = ((ChannelExec) channel).getErrStream();
        InputStreamReader errStrRdr = new InputStreamReader(err, "UTF-8");
        Reader errStrBufRdr = new BufferedReader(errStrRdr);
        // Direct stdout output of command
        InputStream out = channel.getInputStream();
        InputStreamReader outStrRdr = new InputStreamReader(out, "UTF-8");
        Reader outStrBufRdr = new BufferedReader(outStrRdr);
        StringBuffer stdout = new StringBuffer();
        StringBuffer stderr = new StringBuffer();
        // timeout after 5 seconds
        channel.connect(5000);
        while (true) {
            if (channel.isClosed()) {
                break;
            }
            // Read from both streams here so that they are not blocked,
            // if they are blocked because the buffer is full, channel.isClosed() will never
            // be true.
            int ch;
            while (outStrBufRdr.ready() && (ch = outStrBufRdr.read()) > -1) {
                stdout.append((char) ch);
            }
            while (errStrBufRdr.ready() && (ch = errStrBufRdr.read()) > -1) {
                stderr.append((char) ch);
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
        }
        // In case there's still some more stuff in the buffers, read them
        int ch;
        while ((ch = outStrBufRdr.read()) > -1) {
            stdout.append((char) ch);
        }
        while ((ch = errStrBufRdr.read()) > -1) {
            stderr.append((char) ch);
        }
        // After the command is executed, gather the results (both stdin and stderr).
        result.append(stdout.toString());
        result.append(stderr.toString());
        // Shutdown the connection
        channel.disconnect();
        session.disconnect();
    } catch (Throwable e) {
        e.printStackTrace();
    // Return empty string if we can't connect.
    }
    return result.toString();
}
Also used : InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JSch(com.jcraft.jsch.JSch) ChannelExec(com.jcraft.jsch.ChannelExec) BufferedReader(java.io.BufferedReader) Session(com.jcraft.jsch.Session)

Example 3 with JSch

use of com.jcraft.jsch.JSch in project voltdb by VoltDB.

the class SSHTools method ScpFrom.

// The Jsch method for SCP from.
// This code is directly copied from the Jsch SCP sample program.  Error handling has been modified by VoltDB.
public boolean ScpFrom(String user, String key, String host, String remote_file, String local_file) {
    FileOutputStream fos = null;
    try {
        String prefix = null;
        if (new File(local_file).isDirectory()) {
            prefix = local_file + File.separator;
        }
        String command = "scp -f " + remote_file;
        cmdLog.debug("CMD: '" + command + "'");
        JSch jsch = new JSch();
        // Set the private key
        if (null != key)
            jsch.addIdentity(key);
        Session session = jsch.getSession(user, host, 22);
        // To avoid the UnknownHostKey issue
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        // exec 'scp -f rfile' remotely
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        // get I/O streams for remote scp
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();
        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 + (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;
                }
            }
            String destination_file = prefix == null ? local_file : prefix + file;
            cmdLog.debug("CMD: scp to local file '" + destination_file + "'");
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
            // read a content of lfile
            fos = new FileOutputStream(destination_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) {
                cmdLog.debug("CMD: scp checkAck failed");
                System.out.println("checkAck did not equal zero.");
                return false;
            }
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
        }
        session.disconnect();
    } catch (Exception e) {
        System.out.println(e);
        cmdLog.debug("CMD: scp failed with exception: " + e.toString());
        return false;
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (Exception ee) {
        }
    }
    return true;
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) JSch(com.jcraft.jsch.JSch) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Session(com.jcraft.jsch.Session)

Example 4 with JSch

use of com.jcraft.jsch.JSch in project azure-sdk-for-java by Azure.

the class ComputeManagementTest method ensureCanDoSsh.

protected void ensureCanDoSsh(String fqdn, int sshPort, String uname, String password) {
    if (IS_MOCKED) {
        return;
    }
    JSch jsch = new JSch();
    com.jcraft.jsch.Session session = null;
    try {
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session = jsch.getSession(uname, fqdn, sshPort);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
    } catch (Exception e) {
        Assert.fail("SSH connection failed" + e.getMessage());
    } finally {
        if (session != null) {
            session.disconnect();
        }
    }
}
Also used : JSch(com.jcraft.jsch.JSch) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException)

Example 5 with JSch

use of com.jcraft.jsch.JSch in project ats-framework by Axway.

the class SftpClient method doConnect.

private void doConnect(String publicKeyAlias) throws FileTransferException {
    // make new SFTP object for every new connection
    disconnect();
    this.jsch = new JSch();
    /* NOTE: Due to logging being global (static), if one thread enables debug mode, all threads will log messages,
         * and if another thread disables it, logging will be stopped for all threads,
         * until at least one thread enables it again
         */
    if (isDebugMode()) {
        JSch.setLogger(new SftpListener());
        debugProgressMonitor = new SftpFileTransferProgressMonitor();
    } else {
        debugProgressMonitor = null;
    }
    try {
        if (username != null) {
            this.session = jsch.getSession(this.username, this.hostname, this.port);
            this.session.setPassword(this.password);
        } else {
            this.jsch.addIdentity(this.keystoreFile, this.publicKeyAlias, this.keystorePassword.getBytes());
            this.session = this.jsch.getSession(this.username, this.hostname, this.port);
        }
        // skip checking of known hosts and verifying RSA keys
        this.session.setConfig("StrictHostKeyChecking", "no");
        // make keyboard-interactive last authentication method
        this.session.setConfig("PreferredAuthentications", "publickey,password,keyboard-interactive");
        this.session.setTimeout(this.timeout);
        if (this.ciphers != null && this.ciphers.size() > 0) {
            StringBuilder ciphers = new StringBuilder();
            for (SshCipher cipher : this.ciphers) {
                ciphers.append(cipher.getSshAlgorithmName() + ",");
            }
            this.session.setConfig("cipher.c2s", ciphers.toString());
            this.session.setConfig("cipher.s2c", ciphers.toString());
            this.session.setConfig("CheckCiphers", ciphers.toString());
        }
        if (this.listener != null) {
            this.listener.setResponses(new ArrayList<String>());
            JSch.setLogger((com.jcraft.jsch.Logger) this.listener);
        }
        /* SFTP reference implementation does not support transfer mode.
               Due to that, JSch does not support it either.
               For now setTransferMode() has no effect. It may be left like that,
               implemented to throw new FileTransferException( "Not implemented" )
               or log warning, that SFTP protocol does not support transfer mode change.
            */
        this.session.connect();
        this.channel = (ChannelSftp) this.session.openChannel("sftp");
        this.channel.connect();
    } catch (JSchException e) {
        throw new FileTransferException("Unable to connect!", e);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) SshCipher(com.axway.ats.common.filetransfer.SshCipher) SftpListener(com.axway.ats.core.filetransfer.model.ftp.SftpListener) JSch(com.jcraft.jsch.JSch) SftpFileTransferProgressMonitor(com.axway.ats.core.filetransfer.model.ftp.SftpFileTransferProgressMonitor)

Aggregations

JSch (com.jcraft.jsch.JSch)122 Session (com.jcraft.jsch.Session)65 JSchException (com.jcraft.jsch.JSchException)48 IOException (java.io.IOException)47 Channel (com.jcraft.jsch.Channel)32 Properties (java.util.Properties)27 InputStream (java.io.InputStream)26 ChannelExec (com.jcraft.jsch.ChannelExec)25 File (java.io.File)25 ChannelSftp (com.jcraft.jsch.ChannelSftp)20 KeyPair (com.jcraft.jsch.KeyPair)19 BufferedReader (java.io.BufferedReader)16 UserInfo (com.jcraft.jsch.UserInfo)14 InputStreamReader (java.io.InputStreamReader)14 ByteArrayOutputStream (java.io.ByteArrayOutputStream)13 SftpException (com.jcraft.jsch.SftpException)10 FileInputStream (java.io.FileInputStream)10 OutputStream (java.io.OutputStream)10 FileOutputStream (java.io.FileOutputStream)6 Test (org.junit.Test)5