使用ssh私钥连接会话时出错

问题描述 投票:0回答:1

我是新手,所以任何帮助将不胜感激。我正在尝试使用私有ssh密钥和JSch连接到生产服务器,代码是:

private static Logger log = Logger.getLogger(SSHKeyConnector.class);

private final static String HOST_KEY_CHECKING           = "StrictHostKeyChecking";
private final static String HOST_KEY_CHECKING_OPTION    = "no";
private final static String AUTHENTICATION              = "PreferredAuthentications";
private final static String AUTHENTICATION_STYLE        = "publickey,keyboard-interactive,password";
private Session      session;

public SSHKeyConnector() {}

public Session createSession( DataTransferParameterCollection parameters ) throws RemoteAccessException {

    String  host        = parameters.getHostname();
    int     port        = parameters.getPort();
    String  user        = parameters.getHostUser();
    String  password    = parameters.getHostPassword();
    String  keyFile     = parameters.getKeyDirectory() + "id_rsa";

    JSch jsch = new JSch();

    try {
        log.debug("Create an ssh connection to [" + host + "][" + port + "] as user [" + user + "]");

        jsch.addIdentity( keyFile );
        log.debug("Key file added to session");

        session = jsch.getSession( user, host, port );
        session.setConfig(AUTHENTICATION, AUTHENTICATION_STYLE);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");

        session.setConfig(config);
        session.setPassword( password );
        session.connect();
        log.debug("Remote session connected");

        return session;
    }
    catch ( JSchException je ) {
        log.debug("CreateSession failed: " + je.getCause() );
        je.printStackTrace();
        throw new RemoteAccessException( "CreateSession failed: " + je.getCause());
    }
}

当我运行这个时,我仍然收到身份验证错误,我在StackOverflow上检查了很多帖子,但看不出有什么问题

2019-03-28 11:04:35 DEBUG SSHKeyConnector:? - Key file added to session
2019-03-28 11:04:35 DEBUG SSHKeyConnector:? - CreateSession failed: null
com.jcraft.jsch.JSchException: USERAUTH fail
        at com.jcraft.jsch.UserAuthPublicKey.start(UserAuthPublicKey.java:119)
        at com.jcraft.jsch.Session.connect(Session.java:470)
        at com.jcraft.jsch.Session.connect(Session.java:183)
        at com.floristpro.migrate.dao.utilities.SSHKeyConnector.createSession(Unknown Source)
        at com.floristpro.migrate.dao.RemoteAccessDAO.downloadDBandImages(Unknown Source)
        at com.floristpro.migrate.service.RemoteAccessService.downloadDBandImages(Unknown Source)
        at com.floristpro.migrate.DataDownload.run(Unknown Source)
        at com.floristpro.migrate.DataDownload.main(Unknown Source)
2019-03-28 11:04:35 ERROR RemoteAccessDAO:? - Remote Access Error: CreateSession failed: null
jsch
1个回答
0
投票

感谢您的回复,我通过改变它来实现这一点

jsch.addIdentity(密钥文件);

jsch.addIdentity(密钥文件,密码);

并已删除

session.setPassword(密码);

它现在工作正常

© www.soinside.com 2019 - 2024. All rights reserved.