java sftp 密钥链接

source code

package com.shiyin.study.toolset.sshTool;

import com.jcraft.jsch.*;

import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;


public class SshTool {
    public static void main(String[] args) {
        new SshTool().config();
    }
    public void config() {
        //从配置文件中读取 目标服务器ip、端口、用户名、私钥路径
//       String ftpHost = prop.getProperty("downloadHost");
//       String port = prop.getProperty("downloadftpPort");
//       String ftpUserName = prop.getProperty("downloadUserName");
//        String priKeyBasePath = "G:\\study\\toolset\\MostUsedTool\\src\\main\\resources\\id_rsa";
        String priKeyBasePath = "C:\\Users\\Administrator\\.ssh\\id_rsa";
        //建立JSch对象


        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp channelSftp = null;
        try {
            //添加私钥
            jsch.addIdentity(priKeyBasePath);
            jsch.setKnownHosts("C:\\Users\\Administrator\\.ssh\\known_hosts");
            session = jsch.getSession("root", "39.106.59.67", 22);
            Properties sessionConfig = new Properties();
            //SSH 公钥检查机制 no、ask、yes
            sessionConfig.put("StrictHostKeyChecking", "no");
            session.connect();

            channelSftp = (ChannelSftp) session.openChannel("sftp"); // 打开SFTP通道
            channelSftp.connect();
            //进行操作 如进入指定文件夹
            channelSftp.cd("/tmp");
            Vector ls = channelSftp.ls("/tmp");
            for (Object l : ls) {
                System.out.println(l);
            }
        } catch (
                JSchException | SftpException e) {
            System.out.println(e);
        }
    }
}

Notes:

如果连接不到机器上,第一次使用command 连接到remote server上

Invalidate private key

主要原因是ssh版本过高,使用下面命令生成低版本的

ssh-keygen -m PEM -t rsa -b 4096

pom依赖

 <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值