2012年10月18日 星期四

j2ssh



[NOTE]
用j2ssh使用java進行SSH連線並下指令的小範例


import com.sshtools.j2ssh.*;
import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification;
import com.sshtools.j2ssh.authentication.*;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.session.SessionOutputReader;


String user = "user";
String passwd = "123456";
String host = "111.111.111.111";
String port = "22";
//先建立好一個使用者的認證,並給他帳號密碼資訊
PasswordAuthenticationClient auth = new PasswordAuthenticationClient();
auth.setUsername(user);
auth.setPassword(passwd);


try { //必須catch

            //建立一個空的client物件,並給他連線資訊
            SshClient client = new SshClient();
            client.connect(host, 22, new IgnoreHostKeyVerification());

            //利用這個client物件,使用剛剛建立的使用者認證來進行登入
            int result = client.authenticate(auth);
            if(result== AuthenticationProtocolState.COMPLETE){
                        System.out.println("OK");
            }
            else{
                        System.out.println(result);
            }

            //成功登入就建立一個空的session 準備進行對話
            SessionChannelClient session = new SessionChannelClient();
            //替這個session物件開啟一個對話用的Channel
            session = client.openSessionChannel();
           //開始對話
            if (session.startShell()){
             
            }
           //建立一個Output Stream ,並且把他關連到剛剛建立的session         
            OutputStream writer = session.getOutputStream();
          //建立一個專門讀output Stream的Reader,關連到session
            SessionOutputReader sor = new SessionOutputReader(session);
          //下指令
            writer.write("pwd\n".getBytes());
          //一定要等一下,不然機器還沒返回結果你就去讀會得到NULL
            Thread.sleep(3000);        
          //從Reader拿到Stream的資料
            String line = sor.getOutput();        
            System.out.println(line);
          //還要下指令的話就繼續write、繼續等、繼續getOutput
          //有始有終
            session.close();
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }

沒有留言:

終焉に咲く花-Asriel