2011-04-06 39 views
5

我使用ssh工具來建立到學校服務器的ssh連接,我使用的是一個來自ssh連接源的例子。我的問題是我不想要任何用戶輸入提示,但是彈出一個提示說主機的真實性無法建立,用戶需要按yes才能繼續,我該如何編寫程序以接受提示本身。UserInfo通過是點擊功能

Session session = jsch.getSession(user, host, 22); 
//username and host I can input directly into program so thats not a problem 
// username and password will be given via UserInfo interface. 
UserInfo ui = new MyUserInfo(); 

//this is the part that uses the UserInfo, which pulls up a prompt 
//how can I code the prompt to automatically choose yes?  
session.setUserInfo(ui); 
session.setPassword("password"); 
session.connect(); 
String command = JOptionPane.showInputDialog("Enter command", "set|grep SSH"); 

回答

3

我們用下面的代碼:

try { 
    session = jsch.getSession(user, host, port); 
} 
catch (JSchException e) { 
    throw new TransferException("Failed to open session - " + params, e); 
} 

session.setPassword(password); 

// Create UserInfo instance in order to support SFTP connection to any machine 
// without a key username and password will be given via UserInfo interface. 
UserInfo userInfo = new SftpUserInfo(); 
session.setUserInfo(userInfo); 

try { 
    session.connect(connectTimeout); 
} 
catch (JSchException e) { 
    throw new TransferException("Failed to connect to session - " + params, e); 
} 

boolean isSessionConnected = session.isConnected(); 

,最重要的是:

/** 
* Implements UserInfo instance in order to support SFTP connection to any machine without a key. 
*/ 
class SftpUserInfo implements UserInfo { 

    String password = null; 

    @Override 
    public String getPassphrase() { 
     return null; 
    } 

    @Override 
    public String getPassword() { 
     return password; 
    } 

    public void setPassword(String passwd) { 
     password = passwd; 
    } 

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

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

    @Override 
    public boolean promptYesNo(String message) { 
     return true; 
    } 

    @Override 
    public void showMessage(String message) { 
    } 
} 
+0

工作謝謝你的幫助。 – user541597 2011-04-06 05:48:29

+0

@ user541597最受歡迎 – Yaneeve 2011-04-06 05:50:56

+0

@Yaneeve此程序不會擺脫用戶提示。運行你的代碼時,我可以看到用戶仍然需要點擊輸入。請確認您已經將此代碼說明可以完成此操作來連接遠程服務器,但它無助於自動執行身份驗證過程。 – MKod 2017-11-14 13:06:07