Search in sources :

Example 91 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project boot2 by yangshangwei.

the class SSHUtil method runCommand.

// command 命令
public String runCommand(String command) throws Exception {
    // CommonUtil.printLogging("[" + command + "] begin", host, user);
    this.initialSession();
    InputStream in = null;
    InputStream err = null;
    BufferedReader inReader = null;
    BufferedReader errReader = null;
    int time = 0;
    String s = null;
    boolean run = false;
    StringBuffer sb = new StringBuffer();
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(null);
    err = ((ChannelExec) channel).getErrStream();
    in = channel.getInputStream();
    channel.connect();
    inReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    errReader = new BufferedReader(new InputStreamReader(err, "UTF-8"));
    while (true) {
        s = errReader.readLine();
        if (s != null) {
            sb.append("error:" + s).append("\n");
        } else {
            run = true;
            break;
        }
    }
    while (true) {
        s = inReader.readLine();
        if (s != null) {
            sb.append("info:" + s).append("\n");
        } else {
            run = true;
            break;
        }
    }
    while (true) {
        if (channel.isClosed() || run) {
            // channel.getExitStatus(), host, user);
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
        if (time > 180) {
            // channel.getExitStatus(), host, user);
            break;
        }
        time++;
    }
    inReader.close();
    errReader.close();
    channel.disconnect();
    session.disconnect();
    System.out.println(sb.toString());
    return sb.toString();
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) BufferedReader(java.io.BufferedReader) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 92 with ChannelExec

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

the class SSHCommandLauncher method execute.

@Override
public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, IProgressMonitor monitorm, PTY pty) throws CoreException {
    StringBuilder cmd = new StringBuilder();
    if (changeToDirectory != null)
        // $NON-NLS-1$ //$NON-NLS-2$
        cmd.append("cd " + changeToDirectory.toString() + "; ");
    cmd.append(commandPath.toString());
    // $NON-NLS-1$
    cmd.append(" ");
    if (args != null)
        for (String s : args) {
            // $NON-NLS-1$ //$NON-NLS-2$
            cmd.append("\"" + s + "\"");
            // $NON-NLS-1$
            cmd.append(" ");
        }
    try {
        ChannelExec channel = createChannelExec();
        if (env != null)
            for (String s : env) {
                // $NON-NLS-1$
                String[] tokens = s.split("=", 2);
                switch(tokens.length) {
                    case 1:
                        channel.setEnv(tokens[0], null);
                        break;
                    case 2:
                        channel.setEnv(tokens[0], tokens[1]);
                        break;
                    default:
                        Activator.log(IStatus.WARNING, Messages.SSHCommandLauncher_malformed_env_var_string + s);
                }
            }
        channel.setCommand(cmd.toString());
        channel.connect();
        fProcess = new SSHProcess(channel);
        return fProcess;
    } catch (JSchException e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.SSHCommandLauncher_execution_problem + e.getMessage()));
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) CoreException(org.eclipse.core.runtime.CoreException) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 93 with ChannelExec

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

the class ManParser method execRemote.

private static Channel execRemote(String[] args, OutputStream out, OutputStream err, String user, String host, String password) throws JSchException {
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host, DEFAULT_SSH_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();
    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 94 with ChannelExec

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

the class ConnectorTask method getNMCEvents.

private void getNMCEvents(SQLiteDatabase writablePool, Session session, final UPS ups, final boolean loadEvents) {
    ArrayList<String> events = new ArrayList<>();
    if (loadEvents) {
        Log.i(TAG, "Loading events...");
        try {
            this.connectSSHServer(ups);
            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand("apc-scp -f event.txt");
            channel.connect();
            InputStream in = channel.getInputStream();
            Scanner scanner = new Scanner(in);
            scanner.useDelimiter("\r");
            StringBuilder stringBuilder = new StringBuilder();
            while (scanner.hasNext()) {
                stringBuilder.append(scanner.next());
            }
            String eventsString = stringBuilder.toString();
            if (eventsString.contains("Date,Time,User,Event,Code")) {
                String eventString = eventsString.split("Date,Time,User,Event,Code")[1];
                events.addAll(Arrays.asList(eventString.split("\n")));
            }
            channel.disconnect();
            sessionDisconnect(session);
            databaseHelper.insertEvents(writablePool, ups.UPS_ID, events);
        } catch (JSchException | IOException e) {
            e.printStackTrace();
            apcupsdInterface.onCommandError(e.toString());
            sessionDisconnect(session);
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) Scanner(java.util.Scanner) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 95 with ChannelExec

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

the class ScpClient method transfer.

public void transfer(String fromFile, String toFile) throws IOException, JSchException {
    String rfile = toFile;
    String lfile = fromFile;
    // $NON-NLS-1$
    String command = "scp -t " + rfile;
    // $NON-NLS-1$
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    // get I/O streams for remote scp
    try (OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream()) {
        channel.connect();
        if (checkAck(in) != 0) {
            // $NON-NLS-1$
            System.out.println("err");
        }
        // send "C0644 filesize filename", where filename should not include
        // '/'
        long filesize = (new File(lfile)).length();
        // $NON-NLS-1$ //$NON-NLS-2$
        command = "C0644 " + filesize + " ";
        if (lfile.lastIndexOf('/') > 0) {
            command += lfile.substring(lfile.lastIndexOf('/') + 1);
        } else {
            command += lfile;
        }
        // $NON-NLS-1$
        command += "\n";
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
            // $NON-NLS-1$
            System.out.println("err");
        }
        // send a content of lfile
        byte[] buf = new byte[1024];
        try (FileInputStream fis = new FileInputStream(lfile)) {
            while (true) {
                int len = fis.read(buf, 0, buf.length);
                if (len <= 0) {
                    break;
                }
                out.write(buf, 0, len);
            }
        }
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        if (checkAck(in) != 0) {
            // $NON-NLS-1$
            System.out.println("err");
        }
    }
    channel.disconnect();
    session.disconnect();
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) OutputStream(java.io.OutputStream) File(java.io.File) ChannelExec(com.jcraft.jsch.ChannelExec) FileInputStream(java.io.FileInputStream)

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