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>