Search in sources :

Example 31 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project org.eclipse.linuxtools by eclipse-linuxtools.

the class LinuxtoolsProcessFactory method execRemote.

/**
 * Runs a command on the given host using the given credentials.
 *
 * @param args The command to run, followed by a list of optional arguments.
 * @param out A stream for the command's standard output.
 * @param err A stream for the command's standard error output.
 * @param user the user name to use on the remote machine.
 * @param host the host where the command will be run.
 * @param password password for authenticating with the given host.
 * @param port The port to use during remote communication.
 * @param envp an array with extra enviroment variables to be used when running
 * the command. Set to <code>null</code> if none are needed.
 * @return a {@link Channel} connected to the remotely running process.
 * @throws JSchException thrown if there are problems connecting to the remote machine.
 * @since 3.1
 */
public static Channel execRemote(String[] args, OutputStream out, OutputStream err, String user, String host, String password, int port, String[] envp) throws JSchException {
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host, port);
    session.setPassword(password);
    Properties config = new Properties();
    // $NON-NLS-1$//$NON-NLS-2$
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    StringBuilder command = new StringBuilder();
    if (envp != null) {
        for (String var : envp) {
            // $NON-NLS-1$
            command.append(String.format("export %s; ", var));
        }
    }
    for (int i = 0; i < args.length; i++) {
        command.append(args[i] + ' ');
    }
    // $NON-NLS-1$
    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setPty(true);
    channel.setCommand(command.toString());
    channel.setInputStream(null, true);
    channel.setOutputStream(out, true);
    channel.setExtOutputStream(err, true);
    channel.connect();
    return channel;
}
Also used : JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties) ChannelExec(com.jcraft.jsch.ChannelExec) Session(com.jcraft.jsch.Session)

Example 32 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project Bastillion by bastillion-io.

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)

Example 33 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project apcupsd-monitor by norkator.

the class ConnectorTask method getUPSStatusSSH.

private void getUPSStatusSSH(SQLiteDatabase writablePool, Session session, final UPS ups, final boolean loadEvents) {
    try {
        StringBuilder stringBuilder = new StringBuilder();
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(ups.UPS_SERVER_STATUS_COMMAND);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        InputStream input = channel.getInputStream();
        channel.connect();
        // Can be replaced by test string (/*input*/ testInputStream)
        InputStreamReader inputReader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(inputReader);
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        bufferedReader.close();
        inputReader.close();
        channel.disconnect();
        ContentValues contentValues = new ContentValues();
        contentValues.put(DatabaseHelper.UPS_REACHABLE, UPS.UPS_REACHABLE);
        contentValues.put(DatabaseHelper.UPS_STATUS_STR, stringBuilder.toString());
        databaseHelper.insertUpdateUps(writablePool, ups.UPS_ID, contentValues);
        if (this.taskMode == TaskMode.MODE_ACTIVITY) {
            getUPSEvents(writablePool, session, ups, loadEvents);
        }
    } catch (JSchException | IOException e) {
        e.printStackTrace();
        apcupsdInterface.onCommandError(e.toString());
        sessionDisconnect(session);
    }
}
Also used : ContentValues(android.content.ContentValues) JSchException(com.jcraft.jsch.JSchException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 34 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project ASAP by salmant.

the class DM method How_many_existing_servers.

// ///////////////////////////////////////////
public static int How_many_existing_servers() {
    int i = 0;
    String haproy_ip = "194.249.1.110";
    String haproy_host_user = "root";
    String haproy_host_password = "********************";
    try {
        String command = "cat /etc/haproxy/haproxy.cfg";
        JSch jsch = new JSch();
        com.jcraft.jsch.Session session = jsch.getSession(haproy_host_user, haproy_ip, 22);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        ;
        session.setPassword(haproy_host_password);
        session.connect();
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        InputStream input = channel.getInputStream();
        channel.connect();
        try {
            InputStreamReader inputReader = new InputStreamReader(input);
            BufferedReader bufferedReader = new BufferedReader(inputReader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains("-www"))
                    i++;
            // System.out.println(line);
            }
            bufferedReader.close();
            inputReader.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return i;
        }
        channel.disconnect();
        session.disconnect();
        return i;
    } catch (Exception ex) {
        ex.printStackTrace();
        return i;
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader)

Example 35 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project ASAP by salmant.

the class Run_a_Container method add_to_haproxy.

// ///////////////////////////////////////////////////////////
public void add_to_haproxy() {
    String haproy_ip = "194.249.1.110";
    String haproy_host_user = "root";
    String haproy_host_password = "*****************";
    // ////////////////////////////// add new server
    try {
        String command = "echo " + "\"" + "    server " + i_str + "-www " + new_IP + ":5000 check" + "\"" + ">> /etc/haproxy/haproxy.cfg";
        JSch jsch = new JSch();
        com.jcraft.jsch.Session session = jsch.getSession(haproy_host_user, haproy_ip, 22);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        ;
        session.setPassword(haproy_host_password);
        session.connect();
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        InputStream input = channel.getInputStream();
        channel.connect();
        try {
            InputStreamReader inputReader = new InputStreamReader(input);
            BufferedReader bufferedReader = new BufferedReader(inputReader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
            // System.out.println(line);
            }
            bufferedReader.close();
            inputReader.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        channel.disconnect();
        session.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    // ////////////////////////////// reload HAProxy
    try {
        String command = "sh /haproxy.sh";
        JSch jsch = new JSch();
        com.jcraft.jsch.Session session = jsch.getSession(haproy_host_user, haproy_ip, 22);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        ;
        session.setPassword(haproy_host_password);
        session.connect();
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        InputStream input = channel.getInputStream();
        channel.connect();
        try {
            InputStreamReader inputReader = new InputStreamReader(input);
            BufferedReader bufferedReader = new BufferedReader(inputReader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
            // System.out.println(line);
            }
            bufferedReader.close();
            inputReader.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        channel.disconnect();
        session.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader)

Aggregations

ChannelExec (com.jcraft.jsch.ChannelExec)99 InputStream (java.io.InputStream)63 IOException (java.io.IOException)59 JSchException (com.jcraft.jsch.JSchException)50 Channel (com.jcraft.jsch.Channel)48 Session (com.jcraft.jsch.Session)31 JSch (com.jcraft.jsch.JSch)29 FileInputStream (java.io.FileInputStream)26 InputStreamReader (java.io.InputStreamReader)26 BufferedReader (java.io.BufferedReader)23 OutputStream (java.io.OutputStream)22 File (java.io.File)17 Properties (java.util.Properties)16 FileOutputStream (java.io.FileOutputStream)15 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 SftpException (com.jcraft.jsch.SftpException)6 GFacException (org.apache.airavata.gfac.core.GFacException)6 ArrayList (java.util.ArrayList)5 Charset (java.nio.charset.Charset)4 UserInfo (com.jcraft.jsch.UserInfo)3