【问题标题】:Can we use JSch for SSH key-based communication?我们可以使用 JSch 进行基于 SSH 密钥的通信吗?
【发布时间】:2011-06-23 08:27:13
【问题描述】:

我正在使用JSch 进行 sftp 通信,现在我想使用促进基于密钥的身份验证,密钥由我的网络团队一次加载到客户端和服务器机器上,以后的所有通信都将仅基于用户,我们为此已加载密钥。

sftp -oPort=10022 jmark@192.18.0.246

作为tjill@192.18.0.135

就像这个命令工作正常并连接到 sftp,我如何以编程方式实现这个功能。

如果无法使用 JSch,请推荐其他库。我遇到了Apache SSHD

【问题讨论】:

    标签: java ssh jsch


    【解决方案1】:

    这是可能的。看看JSch.addIdentity(...)

    这允许您将密钥用作字节数组或从文件中读取。

    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    
    public class UserAuthPubKey {
        public static void main(String[] arg) {
            try {
                JSch jsch = new JSch();
    
                String user = "tjill";
                String host = "192.18.0.246";
                int port = 10022;
                String privateKey = ".ssh/id_rsa";
    
                jsch.addIdentity(privateKey);
                System.out.println("identity added ");
    
                Session session = jsch.getSession(user, host, port);
                System.out.println("session created.");
    
                // disabling StrictHostKeyChecking may help to make connection but makes it insecure
                // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
                // 
                // java.util.Properties config = new java.util.Properties();
                // config.put("StrictHostKeyChecking", "no");
                // session.setConfig(config);
    
                session.connect();
                System.out.println("session connected.....");
    
                Channel channel = session.openChannel("sftp");
                channel.setInputStream(System.in);
                channel.setOutputStream(System.out);
                channel.connect();
                System.out.println("shell channel connected....");
    
                ChannelSftp c = (ChannelSftp) channel;
    
                String fileName = "test.txt";
                c.put(fileName, "./in/");
                c.exit();
                System.out.println("done");
    
            } catch (Exception e) {
                System.err.println(e);
            }
        }
    }
    

    【讨论】:

    • 预装在系统中 可能意味着它是.ssh/id_rsa 或类似的,或者.ssh/config 中有针对您的主机的特殊设置,或者您正在使用一些像ssh_agent 这样的程序可以按需提供密钥。探索哪种情况适合您,并将其添加到您的问题中。
    • 就我而言,我还需要提供 UserInfo:session.setUserInfo(userinfo)。没有它我得到JSchException: USERAUTH fail
    • @Betlista 当您使用ssh -i 时,不指定用户名,它使用客户端计算机上帐户的用户名。因此,如果您以 steve@client 身份登录,则相当于说 ssh -i /path/to/private_key steve@remote
    • @Martin - 我更新了代码示例,其中包含指向您 SO 答案的链接。现在应该清楚禁用 StrictHostKeyChecking 是不安全的。
    • 补充一点:还有一个addIdentity() 方法可以接受密钥和密码,所以你不需要处理UserInfo-Object
    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 2014-08-04
    • 2016-05-01
    • 1970-01-01
    • 2019-02-12
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多