JSch的使用與加載.ppk檔案的注意事項
JSch作為一個連接配接sftp的開源的jar包,使用時應該遵循下面幾點注意事項
- 如果私鑰檔案時putty生成的.ppk檔案,那麼為避免一系列麻煩事請遵循以下幾點
- jdk版本:1.8
- JSch版本:0.1.55以上
private String ftpServer;//登入伺服器位址
private String ftpUser;//登入使用者
private String ftpPassword;//登入使用者密碼
private String ftpPrivateFilePath;//私鑰證書檔案路徑
private String ftpPassphrase;//私鑰證書密碼
private int ftpPort;//登入伺服器端口
JSch jsch = new JSch();
if (ftpPrivateFilePath != null) {
if (ftpPassphrase != null && !"".equals(ftpPassphrase)) {
jsch.addIdentity(ftpPrivateFilePath, ftpPassphrase);// 設定私鑰
} else {
jsch.addIdentity(ftpPrivateFilePath);// 設定私鑰
}
}
sshSession = jsch.getSession(ftpUser, ftpServer, ftpPort);
if (ftpPassword != null && !"".equals(ftpPassword)) {
sshSession.setPassword(ftpPassword);
}
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
log.info("SFTP:完成建立SFTP Session,準備建立SFTP Channel");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
log.info("SFTP:完成建立SFTP Channel");