Search in sources :

Example 11 with Session

use of com.jcraft.jsch.Session in project GNS by MobilityFirst.

the class SFTPUpload method authenticateSftp.

private static ChannelSftp authenticateSftp(String user, String host, File keyFile) throws JSchException {
    Session session;
    Channel channel;
    JSch jsch = new JSch();
    session = SSHClient.authenticateWithKey(jsch, user, host, keyFile);
    session.connect();
    channel = session.openChannel("sftp");
    channel.connect();
    return (ChannelSftp) channel;
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) Channel(com.jcraft.jsch.Channel) JSch(com.jcraft.jsch.JSch) Session(com.jcraft.jsch.Session)

Example 12 with Session

use of com.jcraft.jsch.Session in project GNS by MobilityFirst.

the class Sudo method main.

/**
   *
   * @param arg
   */
public static void main(String[] arg) {
    try {
        JSch jsch = new JSch();
        Session session = SSHClient.authenticateWithKey(jsch, null, null, null);
        UserInfo ui = new UserInfoPrompted();
        session.setUserInfo(ui);
        session.connect();
        String command = JOptionPane.showInputDialog("Enter command, execed with sudo", "printenv SUDO_USER");
        String sudo_pass = null;
        {
            JTextField passwordField = new JPasswordField(8);
            Object[] ob = { passwordField };
            int result = JOptionPane.showConfirmDialog(null, ob, "Enter password for sudo", JOptionPane.OK_CANCEL_OPTION);
            if (result != JOptionPane.OK_OPTION) {
                System.exit(-1);
            }
            sudo_pass = passwordField.getText();
        }
        Channel channel = session.openChannel("exec");
        // man sudo
        //   -S  The -S (stdin) option causes sudo to read the password from the
        //       standard input instead of the terminal device.
        //   -p  The -p (prompt) option allows you to override the default
        //       password prompt and use a custom one.
        ((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
        InputStream in = channel.getInputStream();
        OutputStream out = channel.getOutputStream();
        ((ChannelExec) channel).setErrStream(System.err);
        ((ChannelExec) channel).setPty(true);
        channel.connect();
        out.write((sudo_pass + "\n").getBytes());
        out.flush();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
    } catch (JSchException | HeadlessException | IOException e) {
        System.out.println(e);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) UserInfoPrompted(edu.umass.cs.aws.networktools.UserInfoPrompted) HeadlessException(java.awt.HeadlessException) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) OutputStream(java.io.OutputStream) UserInfo(com.jcraft.jsch.UserInfo) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) JTextField(javax.swing.JTextField) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) HeadlessException(java.awt.HeadlessException) JSchException(com.jcraft.jsch.JSchException) JPasswordField(javax.swing.JPasswordField) Session(com.jcraft.jsch.Session)

Example 13 with Session

use of com.jcraft.jsch.Session 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 14 with Session

use of com.jcraft.jsch.Session 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 15 with Session

use of com.jcraft.jsch.Session 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)

Aggregations

Session (com.jcraft.jsch.Session)41 JSch (com.jcraft.jsch.JSch)23 JSchException (com.jcraft.jsch.JSchException)20 IOException (java.io.IOException)16 Channel (com.jcraft.jsch.Channel)13 ChannelSftp (com.jcraft.jsch.ChannelSftp)11 File (java.io.File)9 ChannelExec (com.jcraft.jsch.ChannelExec)7 SftpException (com.jcraft.jsch.SftpException)7 InputStream (java.io.InputStream)7 FileInputStream (java.io.FileInputStream)6 UserInfo (com.jcraft.jsch.UserInfo)5 OutputStream (java.io.OutputStream)5 EditableDockerHost (com.microsoft.azure.docker.model.EditableDockerHost)4 DockerHost (com.microsoft.azure.docker.model.DockerHost)3 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)3 AzureDockerPreferredSettings (com.microsoft.azure.docker.model.AzureDockerPreferredSettings)2 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)2 AzureInputDockerLoginCredsDialog (com.microsoft.azuretools.docker.ui.dialogs.AzureInputDockerLoginCredsDialog)2 AzureInputDockerLoginCredsDialog (com.microsoft.intellij.docker.dialogs.AzureInputDockerLoginCredsDialog)2