我们可以使用 JSch 进行基于 SSH 密钥的通信吗? [英] Can we use JSch for SSH key-based communication?

查看:56
本文介绍了我们可以使用 JSch 进行基于 SSH 密钥的通信吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using JSch for sftp communication, now i want to use facilitate the key-based authentication, key is loaded on client and server machine once by my network team and all later communication would be only user based for which we have loaded the key.

sftp -oPort=10022 jmark@192.18.0.246

as tjill@192.18.0.135

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

like this command work fine and connect to the sftp, how i can achieve this functionality programmatically.

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

if it is not possible using JSch, please suggest some other library. I came across Apache SSHD.

推荐答案

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

It is possible. Have a look at JSch.addIdentity(...)

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

This allows you to use key either as byte array or to read it from file.

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

这篇关于我们可以使用 JSch 进行基于 SSH 密钥的通信吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆