简体   繁体   中英

ssh appliance through Java, execuate commands and get response from commands

I am trying to ssh an appliance through java code and I encountered with errors. I am using ( http://www.jcraft.com/ )'s jar. Now here are my problems

  • How can I execuate multiple commands in chell using java? (jcreft lib or someother)
  • How can get output from following code (conversion of outputstream)

     OutputStream out = System.out; PrintStream ps = new PrintStream(out); 

    Here is code's snap

     public static String LoginAppliance(String host, String ID )throws JSchException, InterruptedException, IOException { String result=""; String command = "_shell\\n"; JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(10*1000); Channel channel = session.openChannel("shell"); InputStream is = new ByteArrayInputStream(command.getBytes()); channel.setInputStream(is); channel.setOutputStream(System.out); OutputStream out = System.out; PrintStream ps = new PrintStream(out); channel.connect(15 * 1000); Thread.sleep(3*1000); channel.disconnect(); session.disconnect(); return (result); } 

It will really helpful for me.

  1. Multiple commands can be separated by a semicolon ( ; ) like:

     String command = "echo 'hello';echo 'hello2'\\n"; 
  2. To get the result as a string instead of printing it to the console like:

     ByteArrayOutputStream out = new ByteArrayOutputStream(); channel.setOutputStream(out); ... return out.toString(); 

I misunderstood the question. I took a look on the documentation of Jsch and this was the easiest way for me to make it work:

import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class Main {

    public static void main(String[] args) {
        String host = "theAddress";
        String user = "root";
        String password = "thePassword";

        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(10000);
            System.out.println("-->" + runCommand("echo 'hello'", session)); // -->hello
            System.out.println("-->" + runCommand("whoami", session)); // -->root
            System.out.println("-->" + runCommand("date", session)); // -->Thu Mar 13 23:45:39 CET 2014
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.disconnect();
            }
        }

    }

    private static String runCommand(String string, Session session) {
        ChannelExec channel = null;
        try {
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(string);
            channel.connect();
            return readOutput(channel);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
        }
        return null;
    }

    private static String readOutput(ChannelExec channel) throws IOException {
        // code from: http://www.jcraft.com/jsch/examples/Exec.java.html
        StringBuilder sb = new StringBuilder();
        InputStream in = channel.getInputStream();
        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()) {
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception e) {}
        }
        return sb.toString();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM