2011-04-06 41 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