Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserInfo passing yes click to function

Tags:

java

ssh

I am using ssh tools to make a ssh connection to a school server, the example I am using an example from the source that makes an ssh connection. My problem is I don't want any user input prompts however a prompt pops up saying the authenticity of host can't be established and the user needs to press yes to continue, how can I code it for the program to accept the prompt by itself.

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");
like image 658
user541597 Avatar asked Apr 06 '11 05:04

user541597


1 Answers

We use the code below:

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();

and most importantly:

/**
 * 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) {
    }
}
like image 176
Yaneeve Avatar answered Sep 28 '22 19:09

Yaneeve