SWT SSH terminal

jsch-0.1.50 配合 SWT元件做出簡單的SSH client

重點應該是如何把jsch channel的inputstream, outputStream導入到text

channel.getInputStream()<--顯示ssh的feedback

channel.getOutputStream()<--用來下command


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

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;

public class SshClient {

    private ButtonListener buttonListener;
    private Display display;
    private Shell shell;
    private Text userT;
    private Text passwdT;
    private Text hostT;
    private Button connect;
    private Text editArea;
    private Channel channel;
   
    public SshClient() {
        buttonListener = new ButtonListener();
       
        display = new Display();
        shell = new Shell(display);
        shell.setLayout(new FillLayout());
        SashForm sash = new SashForm(shell, SWT.HORIZONTAL);

        Composite composite = new Composite(sash, SWT.BORDER);
        composite.setLayout(new GridLayout(3, false));
        composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        final Label userL = new Label(composite, SWT.NONE);
        userL.setText("User Name");
        userL.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false));

        userT = new Text(composite, SWT.BORDER);
        userT.setText("");
        userT.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false));

        final Label space = new Label(composite, SWT.NONE);
        space.setText("");

        final Label passwdL = new Label(composite, SWT.NONE);
        passwdL.setText("Password");
        passwdL.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false));

        passwdT = new Text(composite, SWT.BORDER);
        passwdT.setText("");
        passwdT.setEchoChar('*');
        passwdT.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false));

        final Label space1 = new Label(composite, SWT.NONE);
        space1.setText("");

        final Label hostL = new Label(composite, SWT.NONE);
        hostL.setText("Host Ip");
        hostL.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false));

        hostT = new Text(composite, SWT.BORDER);
        hostT.setText("");
        hostT.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false));

        connect = new Button(composite, SWT.NONE);
        connect.setText("Connect");
        connect.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false));
        connect.addSelectionListener(buttonListener);

        final Composite edit = new Composite(sash, SWT.NONE);
        edit.setLayout(new GridLayout());
        edit.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        editArea = new Text(edit, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL
                | SWT.V_SCROLL);
        editArea.setText("");
        editArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));   
        shell.open();       

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
        display.dispose();
    }

    /**
     * @param args
     */

    public static void main(String[] args) {
        SshClient client = new SshClient();
    }
   
    public class InputLine extends Thread{
        private Text text;
        private InputStream inputstream;       
       
        public InputLine(Text text, InputStream inputStream) {
            this.text = text;
            this.inputstream = inputStream;
        }

        @Override
        public void run() {
            while(true){               
                Display.getDefault().asyncExec(new Runnable() {
                    public void run() {
                        try {
                            byte[] buffer = new byte[inputstream.available()];
                            inputstream.read(buffer);
                            text.append(new String(buffer));
                        } catch (IOException e) {
                            System.out.println("Output error ");
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }
   
    public class OutputLine /*extends Thread*/ implements KeyListener {
        private Text text;
        private OutputStream outputStream;
//        private ByteArrayOutputStream  bufferOutput;
        private StringBuilder stringBuilder;
       
        public OutputLine(Text text, OutputStream outputStream){
            this.text = text;
            this.outputStream = outputStream;
//            bufferOutput = new ByteArrayOutputStream();
            stringBuilder = new StringBuilder();
        }   
       
//        @Override
//        public void run() {
//            while(true){
//                Display.getDefault().asyncExec(new Runnable() {
//                    public void run() {
//                        try {
//                            outputStream.write(bufferOutput.toByteArray());
//                        } catch (IOException e) {
//                            System.out.println("Output error ");
//                            e.printStackTrace();
//                        }
//                        String feedback = bufferOutput.toString();
//                        text.append(feedback);
//                    }
//                });
//            }
//        }
       
        @Override
        public void keyPressed(KeyEvent e) {
            String ch = String.valueOf(e.character);
            //valid command
            if(ch.matches("[A-Za-z0-9]")||e.keyCode==32){
                stringBuilder.append(e.character);
                return;
            }
            //backspace key
            if(ch.equals("\b")){
                int length = stringBuilder.length();
                if(length > 0)
                    stringBuilder.deleteCharAt(length-1);
                return;
            }
           
            try {
                //enter key
                if(ch.equals("\r")){
                    String cmd = stringBuilder.toString()+"\r";
                    this.outputStream.write(cmd.getBytes());
                    this.outputStream.flush();
                    stringBuilder.setLength(0);
                }
            } catch (IOException e1) {
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
           
        }
    }   
   
    private class ButtonListener implements SelectionListener {

        @Override
        public void widgetSelected(SelectionEvent e) {
            if (e.getSource().equals(connect))
                try {
                    JSch jsch = new JSch();
                    String host = hostT.getText().trim();
                    String user = userT.getText().trim();
                    String passwd = passwdT.getText().trim();
                    Session session = jsch.getSession(user, host, 22);
                    session.setPassword(passwd);

                    UserInfo ui = new MyUserInfo() {
                        public void showMessage(String message) {
                            MessageDialog.openError(shell, "Error", message);
                        }

                        public boolean promptYesNo(String message) {
                            return MessageDialog.openConfirm(shell, "Warning",
                                    message);
                        }
                    };

                    session.setUserInfo(ui);

                    session.connect(30000);
                    channel = session.openChannel("shell");
                   
                   
                    InputLine inLine = new InputLine(editArea, channel.getInputStream());                   
                    inLine.start();
                   
                    OutputLine outLine = new OutputLine(editArea, channel.getOutputStream());
                    editArea.addKeyListener(outLine);
                   
                    channel.connect(3000);
                   
                } catch (Exception ee) {
                    System.out.println(ee);
                }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    }
    /*
     * jsch Userinfo 用來做SSH 認證 
    */
    private abstract class MyUserInfo implements UserInfo,
            UIKeyboardInteractive {
        public String getPassword() {
            return null;
        }

        public boolean promptYesNo(String str) {
            return false;
        }

        public String getPassphrase() {
            return null;
        }

        public boolean promptPassphrase(String message) {
            return false;
        }

        public boolean promptPassword(String message) {
            return false;
        }

        public void showMessage(String message) {
        }

        public String[] promptKeyboardInteractive(String destination,
                String name, String instruction, String[] prompt, boolean[] echo) {
            return null;
        }
    }
}

留言

這個網誌中的熱門文章

COSCUP2010

Embedded Tomcat