Search in sources :

Example 46 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project OsmAnd-tools by osmandapp.

the class IndexUploader method uploadToSSH.

public void uploadToSSH(File f, String description, String size, String date, UploadSSHCredentials cred) throws IOException, JSchException {
    log.info("Uploading file " + f.getName() + " " + size + " MB " + date + " of " + description);
    // Upload to ftp
    JSch jSch = new JSch();
    boolean knownHosts = false;
    if (cred.knownHosts != null) {
        jSch.setKnownHosts(cred.knownHosts);
        knownHosts = true;
    }
    if (cred.privateKey != null) {
        jSch.addIdentity(cred.privateKey);
    }
    String serverName = cred.url;
    if (serverName.startsWith("ssh://")) {
        serverName = serverName.substring("ssh://".length());
    }
    Session session = jSch.getSession(cred.user, serverName);
    if (cred.password != null) {
        session.setPassword(cred.password);
    }
    if (!knownHosts) {
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
    }
    String rfile = cred.path + "/" + f.getName();
    String lfile = f.getAbsolutePath();
    session.connect();
    // exec 'scp -t rfile' remotely
    String command = "scp -p -t \"" + rfile + "\"";
    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) {
        channel.disconnect();
        session.disconnect();
        return;
    }
    // send "C0644 filesize filename", where filename should not include '/'
    long filesize = (new File(lfile)).length();
    command = "C0644 " + filesize + " ";
    if (lfile.lastIndexOf('/') > 0) {
        command += lfile.substring(lfile.lastIndexOf('/') + 1);
    } else {
        command += lfile;
    }
    command += "\n";
    out.write(command.getBytes());
    out.flush();
    if (checkAck(in) != 0) {
        channel.disconnect();
        session.disconnect();
        return;
    }
    // send a content of lfile
    FileInputStream fis = new FileInputStream(lfile);
    byte[] buf = new byte[1024];
    try {
        int len;
        while ((len = fis.read(buf, 0, buf.length)) > 0) {
            // out.flush();
            out.write(buf, 0, len);
        }
    } finally {
        fis.close();
    }
    fis = null;
    // send '\0'
    buf[0] = 0;
    out.write(buf, 0, 1);
    out.flush();
    if (checkAck(in) != 0) {
        channel.disconnect();
        session.disconnect();
        return;
    }
    out.close();
    channel.disconnect();
    session.disconnect();
    log.info("Finish uploading file index");
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) ZipOutputStream(java.util.zip.ZipOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CodedOutputStream(com.google.protobuf.CodedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) JSch(com.jcraft.jsch.JSch) ChannelExec(com.jcraft.jsch.ChannelExec) FileInputStream(java.io.FileInputStream) RandomAccessFile(java.io.RandomAccessFile) ZipFile(java.util.zip.ZipFile) File(java.io.File) Session(com.jcraft.jsch.Session)

Example 47 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project CommandHelper by EngineHub.

the class SSHWrapper method SCPFrom.

private static void SCPFrom(String remote, File local, Session session) throws IOException, JSchException {
    // exec 'scp -f rfile' remotely
    String command = "scp -f " + remote;
    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 = checkAckFrom(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;
            }
        }
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        String prefix = null;
        if (local.isDirectory()) {
            prefix = local.getPath() + File.separator;
        }
        // read a content of lfile
        FileOutputStream fos = new FileOutputStream(prefix == null ? local.getPath() : 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;
        checkAckFrom(in);
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
    }
    channel.disconnect();
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 48 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project CommandHelper by EngineHub.

the class SSHWrapper method getRemoteMD5.

private static String getRemoteMD5(String remoteFile, Session session) throws JSchException, IOException {
    ChannelExec channel = null;
    final StringBuilder sb = new StringBuilder();
    try {
        channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand("openssl md5 " + remoteFile);
        channel.setInputStream(null);
        channel.setOutputStream(null);
        channel.setErrStream(System.err);
        InputStream in = channel.getInputStream();
        channel.connect();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                sb.append(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                if (in.available() > 0) {
                    continue;
                }
                if (channel.getExitStatus() != 0) {
                    // Something went wrong, fail the comparison
                    return "invalidMD5sum";
                }
                break;
            }
            try {
                Thread.sleep(1);
            } catch (Exception ee) {
            }
        }
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
    if ("".equals(sb.toString())) {
        // or if the file simply doesn't exist.
        return "invalidMD5sum";
    }
    String opensslReturn = sb.toString();
    // This will be something like MD5(/path/to/file)= 798ffb41da648e405ca160fb547e3a09
    // and we just need 798ffb41da648e405ca160fb547e3a09
    opensslReturn = opensslReturn.replaceAll("MD5\\(.*\\)= ", "");
    return opensslReturn.replaceAll("\n|\r", "");
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) SftpException(com.jcraft.jsch.SftpException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JSchException(com.jcraft.jsch.JSchException)

Example 49 with ChannelExec

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

the class SshContainerProvider method runScriptOnHost.

protected void runScriptOnHost(Session session, String script) throws Exception {
    ChannelExec executor = null;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    try {
        executor = (ChannelExec) session.openChannel("exec");
        executor.setPty(true);
        executor.setCommand(script);
        executor.setOutputStream(output);
        executor.setErrStream(error);
        executor.connect();
        int errorStatus = -1;
        for (int i = 0; !executor.isClosed(); i++) {
            if (i > 0) {
                long delayMs = (long) (200L * Math.pow(i, 2));
                Thread.sleep(delayMs);
            }
            if ((errorStatus = executor.getExitStatus()) != -1) {
                break;
            }
        }
        LOGGER.debug("Output: {}", output.toString());
        LOGGER.debug("Error:  {}", error.toString());
        if (verbose) {
            System.out.println("Output : " + output.toString());
            System.out.println("Error : " + error.toString());
        }
        if (errorStatus != 0) {
            throw new Exception(String.format("%s@%s:%d: received exit status %d executing \n--- command ---\n%s\n--- output ---\n%s\n--- error ---\n%s\n------\n", session.getUserName(), session.getHost(), session.getPort(), executor.getExitStatus(), script, output.toString(), error.toString()));
        }
    } finally {
        if (executor != null) {
            executor.disconnect();
        }
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelExec(com.jcraft.jsch.ChannelExec) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException)

Example 50 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project compss by bsc-wdc.

the class AbstractSSHConnector method tryToExecuteCommand.

private boolean tryToExecuteCommand(String workerIP, String user, boolean setPassword, String passwordOrKeyPair, String command) throws ConnectorException {
    Session session = null;
    ChannelExec exec = null;
    InputStream inputStream = null;
    try {
        // Create session
        session = getSession(workerIP, user, setPassword, passwordOrKeyPair);
        // Configure session
        exec = (ChannelExec) session.openChannel("exec");
        exec.setCommand(command);
        // Waits the command to be executed
        inputStream = exec.getErrStream();
        InputStream stdOut = exec.getInputStream();
        // Execute command
        exec.connect(SERVER_TIMEOUT);
        if (LOGGER.isDebugEnabled()) {
            String output = readInputStream(stdOut);
            LOGGER.debug("Command output: " + output);
        }
        int exitStatus = -1;
        while (exitStatus < 0) {
            exitStatus = exec.getExitStatus();
            if (exitStatus == 0) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Command successfully executed: " + command);
                }
                return true;
            } else if (exitStatus > 0) {
                String output = readInputStream(inputStream);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(ERROR_COMMAND_EXEC + command + " in " + workerIP + ".\nReturned std error: " + output);
                }
                throw new ConnectorException(ERROR_COMMAND_EXEC + command + " in " + workerIP + " (exit status:" + exitStatus + ")");
            }
            LOGGER.debug("Command still on execution");
            try {
                Thread.sleep(RETRY_TIME * S_TO_MS);
            } catch (InterruptedException e) {
                LOGGER.debug("Sleep interrupted");
                Thread.currentThread().interrupt();
            }
        }
    } catch (ConnectorException | IOException | JSchException e) {
        throw new ConnectorException(ERROR_EXCEPTION_EXEC_COMMAND + user + "@" + workerIP, e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOGGER.warn(WARN_INPUTSTREAM_CLOSE);
            }
        }
        if (exec != null && exec.isConnected()) {
            LOGGER.debug("Disconnecting exec channel");
            exec.disconnect();
        }
        if (session != null && session.isConnected()) {
            LOGGER.debug("Disconnecting session");
            session.disconnect();
        }
    }
    return false;
}
Also used : JSchException(com.jcraft.jsch.JSchException) InputStream(java.io.InputStream) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec) 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