JAVA實現與Linux通信(通過SSH協議)

使用InputStream和OutputStream來獲得命令行運行結果和輸入內容是首先需要具備的.
然後要解決SSH連接問題.
在OpenSource項目裏找到了Ganymed SSH-2 for Java .下載後有例子,但是沒有找到有關交互命令的例子.所以自己探索了一下
在網上看有老外討論用這個如何改密碼,基本上的問題都是因爲找不到返回的提示
Linux修改密碼輸入passwd後,首先是輸入當前密碼,然後是輸入兩個新密碼
如果當前密碼輸入錯誤,或者新密碼輸入不符合系統密碼規則要求,會要求重新輸入.如果碰到這種情況,程序很容易進入一個不太好控制的循環.
可能一般人都認爲輸入命令後所有的返回都應該是用session.getStdout();而不是session.getStderr();從方法名稱上看確實如此,一個是取得標準輸出,一個是取得錯誤信息.
其實在輸入passwd後.
Changing password for user [username].
Changing password for [username]
這兩行是需要通過session.getStdout();來獲得的.但是後面的
(current) UNIX password:
New UNIX password:
Retype new UNIX password:
這三行是需要使用sessssion.getStderr();來獲取的
如果用戶輸入沒有通過系統檢測,會返回具體原因,但是都是BAD PASSWORD開始的.
如果最後修改成功了.你也會看到有successfully來表示.這些信息是通過session.getStdout();來獲取的.
現在問題很好解決了吧.
寫了一個類來完成修改密碼的操作
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.io.Debug;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
/**
 *
 * @author leon.lee
 */
public class ChangeEmailPassword {
    private String username = "";
    private String oldpassword = "";
    private Connection conn = null;
    private boolean hasError = false;
    private String ErrorMessage = "";
    private boolean isSuccessfully = false;
    private String SystemMessage = "";
    
    public static final String HOST = "127.0.0.1"; //server ip
    public boolean isSuccessfully(){
        return isSuccessfully;
    }
    public boolean isHasError(){
        return hasError;
    }
    public String getErrorMessage(){
        return ErrorMessage;
    }
    public void setErrorMessage(String msg){
        hasError = true;
        this.ErrorMessage =  msg;
    }
    /**
     * Creates a new instance of <code>ChangeEmailPassword</code>.
     * @param username
     * @param oldpassword
     */
    public ChangeEmailPassword(String username,String oldpassword) {
        this.username = username;
        this.oldpassword = oldpassword;
         try{
             conn = new Connection(HOST);
             conn.connect();
            /* Authenticate */
            boolean isAuthenticated = conn.authenticateWithPassword(username, oldpassword);
            if (isAuthenticated == false) {
                setErrorMessage("Authentication failed.");
                conn=null;
            }
         }catch(Exception e){
             conn.close();
             conn = null;
             System.out.println(e);
         }
    }
    public void setNewPassword(String newpassword) {
        if(hasError){
            return;
        }
        if (conn==null){
            return;
        }
        try{
            Session sess = conn.openSession();
            sess.execCommand("passwd");
            InputStream so = sess.getStdout();
            InputStream err = sess.getStderr();
            OutputStream out = sess.getStdin();
            
            byte[] buffer = new byte[500];//其實沒有必要這麼大.130就差不多了.怕萬一有什麼提示.
            int length = 0;
            length = err.read(buffer);
//            if (length > 0) {
//                System.out.println("#1:"+ new String(buffer, 0, length));
//                //(current) UNIX password:
//            }
            String coldpassword = oldpassword+"\n";
            out.write(coldpassword.getBytes());
            length = err.read(buffer);
//            if (length > 0) {
//                System.out.println("#2:"+ new String(buffer, 0, length));
//                //(current) UNIX password:
//            }
            String cnewpass = newpassword +"\n";
            out.write(cnewpass.getBytes());
            length = err.read(buffer);
            if (length > 0) {
                String rs = new String(buffer, 0, length);
                //System.out.println("#3:"+rs);
                if(rs.indexOf("BAD")>-1){
                    sess.close();
                    conn.close();
                    setErrorMessage(rs);
                    return;
                }
            }
            out.write(cnewpass.getBytes());
            length = so.read(buffer);
            if (length > 0) {
                String rs = new String(buffer, 0, length);
                if(rs.indexOf("successfully")>-1){
                    this.isSuccessfully = true;
                    this.SystemMessage = rs;
                }
            }
            /* Close this session */
            sess.close();
            /* Close the connection */
            conn.close();
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ChangeEmailPassword cep = new ChangeEmailPassword("username", "oldpassword");
        if(cep.isHasError()){
            System.out.println(cep.getErrorMessage());
            cep = null;
            return;
        }
        cep.setNewPassword("newpassword");
        if(cep.isHasError()){
            System.out.println(cep.getErrorMessage());
            cep = null;
            return;
        }
        if(cep.isSuccessfully){
            System.out.println(cep.getSystemMessage());
        }
    }
    /**
     * @return the SystemMessage
     */
    public String getSystemMessage() {
        return SystemMessage;
    }
}
 
把裏面註解掉的System.out.println打開可以看到系統提示的信息.我只保留了最關鍵的信息提示
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章