我正在使用ssh工具与学校服务器建立ssh连接,我使用的示例来自创建ssh连接的源代码。我的问题是我不想要任何用户输入提示但是弹出提示说无法建立主机的真实性并且用户需要按是继续,我怎样才能为程序编写代码以接受提示本身。
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");
答案 0 :(得分:5)
我们使用以下代码:
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) {
}
}