【问题标题】:UserInfo passing yes click to function用户信息通过是点击功能
【发布时间】:2016-03-21 15:11:45
【问题描述】:

我正在使用 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");

【问题讨论】:

    标签: java ssh


    【解决方案1】:

    我们使用下面的代码:

    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) {
        }
    }
    

    【讨论】:

    • @Yaneeve 这个程序没有摆脱用户提示。运行您的代码时,我可以看到该用户仍然必须单击 Enter。请确认您已输入此代码以表明可以这样做以连接远程服务器,但这无助于自动化身份验证过程。
    • 对不起,我已经有好几年没有运行这段代码了。如果没记错的话,我们的代码没有问题,并且在运行时不需要提示作为用户输入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多