Search in sources :

Example 31 with JSch

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

the class SSHClient method exec.

/**
   *
   * @param user
   * @param host
   * @param keyFile
   * @param command
   * @param useSudo
   * @param sudoPasswd
   */
public static void exec(String user, String host, File keyFile, String command, boolean useSudo, String sudoPasswd) {
    if (verbose) {
        System.out.println("Remote execute command on " + host + (useSudo ? " as root user: " : " as user " + user + ": ") + command);
    }
    try {
        JSch jsch = new JSch();
        Session session = authenticateWithKey(jsch, user, host, keyFile);
        // username and password will be given via UserInfo interface.
        UserInfo ui = new UserInfoPrompted();
        session.setUserInfo(ui);
        session.connect();
        if (command == null) {
            command = JOptionPane.showInputDialog("Enter command", "set|grep SSH");
        }
        Channel channel = session.openChannel("exec");
        if (useSudo && sudoPasswd != null) {
            ((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
        } else if (useSudo) {
            ((ChannelExec) channel).setCommand("sudo -p '' " + command);
        } else {
            ((ChannelExec) channel).setCommand(command);
        }
        //      if (useSudo) {
        //        ((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
        //      } else {
        //        ((ChannelExec) channel).setCommand(command);
        //      }
        // ??? NOT SURE WHY THIS IS HERE
        channel.setInputStream(null);
        InputStream in = channel.getInputStream();
        // prep the out channel so we can give a password if it is needed
        OutputStream out = null;
        if (useSudo && sudoPasswd != null) {
            out = channel.getOutputStream();
        }
        ((ChannelExec) channel).setErrStream(System.err);
        // WESTY ADDED THIS *****
        if (useSudo) {
            // fixes "you must have a tty to sudo" problem
            ((ChannelExec) channel).setPty(true);
        }
        channel.connect();
        // suppply the password for sudo
        if (out != null) {
            out.write((sudoPasswd + "\n").getBytes());
            out.flush();
        }
        byte[] tmp = new byte[MAXCOMMANDBYTES];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, MAXCOMMANDBYTES);
                if (i < 0) {
                    break;
                }
                if (!verbose) {
                    System.out.print("o");
                } else {
                    System.out.print(new String(tmp, 0, i));
                }
            }
            if (channel.isClosed()) {
                GNSConfig.getLogger().log(Level.FINE, "exit status: {0}", channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
    } catch (JSchException | IOException e) {
        e.printStackTrace();
        GNSConfig.getLogger().severe(e.toString());
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) FileInputStream(java.io.FileInputStream) 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) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException) Session(com.jcraft.jsch.Session)

Example 32 with JSch

use of com.jcraft.jsch.JSch in project azure-tools-for-java by Microsoft.

the class SparkBatchDebugSession method factory.

/**
     * Create a SparkBatchDebugSession instance for specified host and user
     *
     * @param host The SSH host
     * @param user The SSH user
     * @return an SparkBatchDebugSession instance
     * @throws JSchException JSch operation exceptions
     */
public static SparkBatchDebugSession factory(String host, String user) throws JSchException {
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host);
    java.util.Properties config = new java.util.Properties() {

        {
            put("StrictHostKeyChecking", "no");
        }
    };
    session.setConfig(config);
    return new SparkBatchDebugSession(jsch, session);
}
Also used : JSch(com.jcraft.jsch.JSch) Session(com.jcraft.jsch.Session)

Example 33 with JSch

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

the class SSHTools method long_running_command.

public ProcessData long_running_command(String hostname, String[] command, String processName, OutputHandler handler) {
    try {
        JSch jsch = new JSch();
        // Set the private key
        if (null != m_keyFile)
            jsch.addIdentity(m_keyFile);
        Session session = jsch.getSession(m_username, hostname, 22);
        // To avoid the UnknownHostKey issue
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        // timeout after 5 seconds.
        session.connect(5000);
        return new ProcessData(processName, handler, session, stringify(command));
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Also used : JSch(com.jcraft.jsch.JSch) IOException(java.io.IOException) Session(com.jcraft.jsch.Session)

Example 34 with JSch

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

the class SSHTools method ScpTo.

// The Jsch method for SCP to.
// This code is direcly copied from the Jsch SCP sample program.
public boolean ScpTo(String local_file, String user, String key, String host, String remote_file) {
    FileInputStream fis = null;
    try {
        boolean ptimestamp = true;
        String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + 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);
        // timeout after 5 seconds
        session.connect(5000);
        // exec 'scp -t 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();
        if (checkAck(in) != 0) {
            return false;
        }
        File _lfile = new File(local_file);
        if (ptimestamp) {
            command = "T " + (_lfile.lastModified() / 1000) + " 0";
            // The access time should be sent here,
            // but it is not accessible with JavaAPI ;-<
            command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
            out.write(command.getBytes());
            out.flush();
            if (checkAck(in) != 0) {
                return false;
            }
        }
        // send "C0644 filesize filename", where filename should not include '/'
        long filesize = _lfile.length();
        command = "C0644 " + filesize + " ";
        if (local_file.lastIndexOf('/') > 0) {
            command += local_file.substring(local_file.lastIndexOf('/') + 1);
        } else {
            command += local_file;
        }
        command += "\n";
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
            return false;
        }
        // send a content of lfile
        fis = new FileInputStream(local_file);
        byte[] buf = new byte[1024];
        while (true) {
            int len = fis.read(buf, 0, buf.length);
            if (len <= 0)
                break;
            //out.flush();
            out.write(buf, 0, len);
        }
        fis.close();
        fis = null;
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        if (checkAck(in) != 0) {
            return false;
        }
        out.close();
        channel.disconnect();
        session.disconnect();
    } catch (Exception e) {
        System.out.println(e);
        try {
            if (fis != null)
                fis.close();
        } catch (Exception ee) {
        }
        return false;
    }
    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) FileInputStream(java.io.FileInputStream) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) File(java.io.File) Session(com.jcraft.jsch.Session)

Example 35 with JSch

use of com.jcraft.jsch.JSch in project ignite by apache.

the class StartNodeCallableImpl method call.

/** {@inheritDoc} */
@Override
public ClusterStartNodeResult call() {
    JSch ssh = new JSch();
    Session ses = null;
    try {
        if (spec.key() != null)
            ssh.addIdentity(spec.key().getAbsolutePath());
        ses = ssh.getSession(spec.username(), spec.host(), spec.port());
        if (spec.password() != null)
            ses.setPassword(spec.password());
        ses.setConfig("StrictHostKeyChecking", "no");
        ses.connect(timeout);
        boolean win = isWindows(ses);
        char separator = win ? '\\' : '/';
        spec.fixPaths(separator);
        String igniteHome = spec.igniteHome();
        if (igniteHome == null)
            igniteHome = win ? DFLT_IGNITE_HOME_WIN : DFLT_IGNITE_HOME_LINUX;
        String script = spec.script();
        if (script == null)
            script = DFLT_SCRIPT_LINUX;
        String cfg = spec.configuration();
        if (cfg == null)
            cfg = "";
        String startNodeCmd;
        String scriptOutputFileName = FILE_NAME_DATE_FORMAT.format(new Date()) + '-' + UUID.randomUUID().toString().substring(0, 8) + ".log";
        if (win)
            throw new UnsupportedOperationException("Apache Ignite cannot be auto-started on Windows from IgniteCluster.startNodes(…) API.");
        else {
            // Assume Unix.
            int spaceIdx = script.indexOf(' ');
            String scriptPath = spaceIdx > -1 ? script.substring(0, spaceIdx) : script;
            String scriptArgs = spaceIdx > -1 ? script.substring(spaceIdx + 1) : "";
            String rmtLogArgs = buildRemoteLogArguments(spec.username(), spec.host());
            String tmpDir = env(ses, "$TMPDIR", "/tmp/");
            String scriptOutputDir = tmpDir + "ignite-startNodes";
            shell(ses, "mkdir " + scriptOutputDir);
            // Mac os don't support ~ in double quotes. Trying get home path from remote system.
            if (igniteHome.startsWith("~")) {
                String homeDir = env(ses, "$HOME", "~");
                igniteHome = igniteHome.replaceFirst("~", homeDir);
            }
            startNodeCmd = new SB().a("nohup ").a("\"").a(igniteHome).a('/').a(scriptPath).a("\"").a(" ").a(scriptArgs).a(!cfg.isEmpty() ? " \"" : "").a(cfg).a(!cfg.isEmpty() ? "\"" : "").a(rmtLogArgs).a(" > ").a(scriptOutputDir).a("/").a(scriptOutputFileName).a(" 2>& 1 &").toString();
        }
        info("Starting remote node with SSH command: " + startNodeCmd, spec.logger(), log);
        shell(ses, startNodeCmd);
        return new ClusterStartNodeResultImpl(spec.host(), true, null);
    } catch (IgniteInterruptedCheckedException e) {
        return new ClusterStartNodeResultImpl(spec.host(), false, e.getMessage());
    } catch (Exception e) {
        return new ClusterStartNodeResultImpl(spec.host(), false, X.getFullStackTrace(e));
    } finally {
        if (ses != null && ses.isConnected())
            ses.disconnect();
    }
}
Also used : IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) ClusterStartNodeResultImpl(org.apache.ignite.internal.cluster.ClusterStartNodeResultImpl) JSch(com.jcraft.jsch.JSch) Date(java.util.Date) IOException(java.io.IOException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) JSchException(com.jcraft.jsch.JSchException) Session(com.jcraft.jsch.Session) SB(org.apache.ignite.internal.util.typedef.internal.SB)

Aggregations

JSch (com.jcraft.jsch.JSch)35 Session (com.jcraft.jsch.Session)23 JSchException (com.jcraft.jsch.JSchException)16 IOException (java.io.IOException)14 Channel (com.jcraft.jsch.Channel)8 ChannelExec (com.jcraft.jsch.ChannelExec)7 File (java.io.File)7 InputStream (java.io.InputStream)7 ChannelSftp (com.jcraft.jsch.ChannelSftp)6 FileInputStream (java.io.FileInputStream)6 OutputStream (java.io.OutputStream)6 UserInfo (com.jcraft.jsch.UserInfo)5 Properties (java.util.Properties)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 KeyPair (com.jcraft.jsch.KeyPair)2 SftpException (com.jcraft.jsch.SftpException)2 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)2 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)2 UserInfoPrompted (edu.umass.cs.aws.networktools.UserInfoPrompted)2 HeadlessException (java.awt.HeadlessException)2