Search in sources :

Example 66 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project ant-ivy by apache.

the class SshRepository method list.

/*
     * (non-Javadoc)
     *
     * @see org.apache.ivy.repository.Repository#list(java.lang.String)
     */
public List<String> list(String parent) throws IOException {
    Message.debug("SShRepository:list called: " + parent);
    List<String> result = new ArrayList<>();
    Session session = null;
    ChannelExec channel = null;
    session = getSession(parent);
    channel = getExecChannel(session);
    URI parentUri = null;
    try {
        parentUri = new URI(parent);
    } catch (URISyntaxException e) {
        throw new IOException("The uri '" + parent + "' is not valid!", e);
    }
    String fullCmd = replaceArgument(listCommand, parentUri.getPath());
    channel.setCommand(fullCmd);
    StringBuilder stdOut = new StringBuilder();
    StringBuilder stdErr = new StringBuilder();
    readSessionOutput(channel, stdOut, stdErr);
    if (channel.getExitStatus() != 0) {
        Message.error("Ssh ListCommand exited with status != 0");
        Message.error(stdErr.toString());
        return null;
    } else {
        BufferedReader br = new BufferedReader(new StringReader(stdOut.toString()));
        String line = null;
        while ((line = br.readLine()) != null) {
            result.add(line);
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) ChannelExec(com.jcraft.jsch.ChannelExec) Session(com.jcraft.jsch.Session)

Example 67 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project ant-ivy by apache.

the class SshRepository method makePath.

/**
 * Tries to create a directory path on the target system
 *
 * @param path
 *            to create
 * @param session
 *            to use
 */
private void makePath(String path, Session session) throws IOException {
    ChannelExec channel = null;
    String trimmed = path;
    try {
        while (trimmed.length() > 0 && trimmed.charAt(trimmed.length() - 1) == fileSeparator) {
            trimmed = trimmed.substring(0, trimmed.length() - 1);
        }
        if (trimmed.length() == 0 || checkExistence(trimmed, session)) {
            return;
        }
        int nextSlash = trimmed.lastIndexOf(fileSeparator);
        if (nextSlash > 0) {
            String parent = trimmed.substring(0, nextSlash);
            makePath(parent, session);
        }
        channel = getExecChannel(session);
        String mkdir = replaceArgument(createDirCommand, trimmed);
        Message.debug("SShRepository: trying to create path: " + mkdir);
        channel.setCommand(mkdir);
        StringBuilder stdOut = new StringBuilder();
        StringBuilder stdErr = new StringBuilder();
        readSessionOutput(channel, stdOut, stdErr);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
Also used : ChannelExec(com.jcraft.jsch.ChannelExec) TimeoutConstraint(org.apache.ivy.core.settings.TimeoutConstraint)

Example 68 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project ant-ivy by apache.

the class SshRepository method checkExistence.

/**
 * check for existence of file or dir on target system
 *
 * @param filePath
 *            to the object to check
 * @param session
 *            to use
 * @return true: object exists, false otherwise
 */
private boolean checkExistence(String filePath, Session session) throws IOException {
    Message.debug("SShRepository: checkExistence called: " + filePath);
    ChannelExec channel = null;
    channel = getExecChannel(session);
    String fullCmd = replaceArgument(existCommand, filePath);
    channel.setCommand(fullCmd);
    StringBuilder stdOut = new StringBuilder();
    StringBuilder stdErr = new StringBuilder();
    readSessionOutput(channel, stdOut, stdErr);
    return channel.getExitStatus() == 0;
}
Also used : ChannelExec(com.jcraft.jsch.ChannelExec)

Example 69 with ChannelExec

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

the class StartNodeCallableImpl method exec.

/**
 * Executes command using {@code exec} channel with setting encoding.
 *
 * @param ses SSH session.
 * @param cmd Command.
 * @param encoding Process output encoding, {@code null} for default charset encoding.
 * @return Output result.
 * @throws JSchException In case of SSH error.
 * @throws IOException If failed.
 */
private String exec(Session ses, final String cmd, String encoding) throws JSchException, IOException {
    ChannelExec ch = null;
    try {
        ch = (ChannelExec) ses.openChannel("exec");
        ch.setCommand(cmd);
        ch.connect();
        if (encoding == null)
            encoding = Charset.defaultCharset().name();
        GridTimeoutObject to = null;
        SB out = null;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(ch.getInputStream(), encoding))) {
            String line;
            boolean first = true;
            while ((line = reader.readLine()) != null) {
                if (first)
                    out = new SB();
                else
                    out.a('\n');
                out.a(line);
                if (first) {
                    to = initTimer(cmd);
                    first = false;
                }
            }
        } catch (InterruptedIOException ignore) {
        // No-op.
        } finally {
            if (to != null) {
                boolean r = proc.removeTimeoutObject(to);
                assert r || to.endTime() <= U.currentTimeMillis() : "Timeout object was not removed: " + to;
            }
        }
        return out == null ? null : out.toString();
    } finally {
        if (ch != null && ch.isConnected())
            ch.disconnect();
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) ChannelExec(com.jcraft.jsch.ChannelExec) GridTimeoutObject(org.apache.ignite.internal.processors.timeout.GridTimeoutObject) SB(org.apache.ignite.internal.util.typedef.internal.SB)

Example 70 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project KeyBox by skavanagh.

the class SSHUtil method addPubKey.

/**
 * distributes authorized keys for host system
 *
 * @param hostSystem      object contains host system information
 * @param session         an established SSH session
 * @param appPublicKey    application public key value
 * @return status of key distribution
 */
public static HostSystem addPubKey(HostSystem hostSystem, Session session, String appPublicKey) {
    try {
        String authorizedKeys = hostSystem.getAuthorizedKeys().replaceAll("~\\/|~", "");
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand("cat " + authorizedKeys);
        ((ChannelExec) channel).setErrStream(System.err);
        channel.setInputStream(null);
        InputStream in = channel.getInputStream();
        InputStreamReader is = new InputStreamReader(in);
        BufferedReader reader = new BufferedReader(is);
        channel.connect(CHANNEL_TIMEOUT);
        String appPubKey = appPublicKey.replace("\n", "").trim();
        StringBuilder existingKeysBuilder = new StringBuilder();
        String currentKey;
        while ((currentKey = reader.readLine()) != null) {
            existingKeysBuilder.append(currentKey).append("\n");
        }
        String existingKeys = existingKeysBuilder.toString();
        existingKeys = existingKeys.replaceAll("\\n$", "");
        reader.close();
        // disconnect
        channel.disconnect();
        StringBuilder newKeysBuilder = new StringBuilder();
        if (keyManagementEnabled) {
            // get keys assigned to system
            List<String> assignedKeys = PublicKeyDB.getPublicKeysForSystem(hostSystem.getId());
            for (String key : assignedKeys) {
                newKeysBuilder.append(key.replace("\n", "").trim()).append("\n");
            }
            newKeysBuilder.append(appPubKey);
        } else {
            if (existingKeys.indexOf(appPubKey) < 0) {
                newKeysBuilder.append(existingKeys).append("\n").append(appPubKey);
            } else {
                newKeysBuilder.append(existingKeys);
            }
        }
        String newKeys = newKeysBuilder.toString();
        if (!newKeys.equals(existingKeys)) {
            log.info("Update Public Keys  ==> " + newKeys);
            channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand("echo '" + newKeys + "' > " + authorizedKeys + "; chmod 600 " + authorizedKeys);
            ((ChannelExec) channel).setErrStream(System.err);
            channel.setInputStream(null);
            channel.connect(CHANNEL_TIMEOUT);
            // disconnect
            channel.disconnect();
        }
    } catch (JSchException | SQLException | IOException | GeneralSecurityException ex) {
        log.error(ex.toString(), ex);
    }
    return hostSystem;
}
Also used : JSchException(com.jcraft.jsch.JSchException) InputStreamReader(java.io.InputStreamReader) SQLException(java.sql.SQLException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec) BufferedReader(java.io.BufferedReader)

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