如何在JSch中使用id_rsa.pub文件

时间:2014-10-25 11:38:10

标签: java ssh sftp jsch private-key

使用JSch()连接远程SFTP服务器时遇到问题。除了 id_rsa.pub 文件和主机名以及 host_ip_address 之外,我没有任何关于要连接的远程服务器的访问权限或信息。并且该文件中的密钥在远程服务器中注册为授权密钥。因为我能够从shell登录到远程服务器。

sftp -o BindAddress=SOME_IP_ADDRRESS myUserName@HOST_IP_ADDR

工作正常。但是,当我尝试使用JSch时,它不起作用。我所做的是:

  1. 我使用ssh keygen从id_rsa.pub文件中的公钥创建了一个私钥。

  2. 公钥格式为

    ssh-rsa AA.... == someuser@something.com

  3. 我从keygen生成的私钥就像

  4. -----开始RSA私钥-----

      KIOPU.....
    

    ----- END RSA私钥-----

    我在我的session.addIdentity(private_key_file_path);

    中使用此私钥文件

    但是它给了auth_failure异常,我做错了什么

    代码是:

    /* KEY_FILE_NAME = is a file with rsa public key */
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource(KEY_FILE_NAME).getFile());
    JSch jsch = new JSch();
    jsch.addIdentity(file.getAbsolutePath());
    Properties hash = new Properties();
    hash.put("StrictHostKeyChecking", "no");
    logger.debug("SSh Server Host name >>" + SSH_SERVER_HOST_NAME + " || User Name >>" +  SSH_SERVER_USER_NAME);
    
    session = jsch.getSession(SSH_SERVER_USER_NAME, SSH_SERVER_HOST_NAME);
    UserInfo ui = new MyUserInfo();
    session.setUserInfo(ui);
    session.setConfig(hash);
    session.setPort(22);
    session.setTimeout(45000);
    session.setSocketFactory(new SocketFactory() 
    {
        InputStream in = null;
        OutputStream out = null;
    
        public InputStream getInputStream(Socket socket) throws IOException 
        {
            if (in == null)
                in = socket.getInputStream();
            return in;
        }
    
        public OutputStream getOutputStream(Socket socket) throws IOException 
        {
            if (out == null)
                out = socket.getOutputStream();
            return out;
        }
    
        public Socket createSocket(String host, int port) throws IOException, UnknownHostException 
        {
           // The IP Addresses are changed ....
           // using the original IP in my code
            byte[] remoteIpAddr = new byte[] { (byte) 11,(byte) 11, 11, 11 }; 
            byte[] localIpAddr = new byte[] { 55, 55, 55, 55 };
    
            InetAddress remoteIp = InetAddress.getByAddress(remoteIpAddr);
            InetAddress localIp = InetAddress.getByAddress(localIpAddr);
    
            logger.debug("remoteIp >>" + remoteIp.toString());
            logger.debug("localIp >>" + localIp.toString());
            Socket socket = new Socket(remoteIp, 22, localIp, 0);
            logger.debug("socket created >> " + socket.toString());
            return socket;
        }
    });
    session.connect();
    

    请帮忙,我做错了什么......

0 个答案:

没有答案