使用JCSH连接sftp
认证方式为:keyboard-interactive
需要一个用户类来保存密码
代码如下:
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
public class UserClass implements UIKeyboardInteractive, UserInfo {
private String passwd;
@Override
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
String[] response = new String[prompt.length];
response[0] = passwd;
return response;
}
public String getPassphrase() {
return null;
}
public String getPassword() {
return passwd;
}
public void setPassword(String pass) {
this.passwd = pass;
}
public boolean promptPassword(String message) {
return false;
}
public boolean promptPassphrase(String message) {
return false;
}
public boolean promptYesNo(String message) {
return false;
}
public void showMessage(String message) {
}
}
连接sftp
public static void main(String[] args) throws Exception {
String ftpHost = "xxx";
int ftpPort = port;
String userName = "xxx";
String password = "xxx";
MyJschLogger logger = new MyJschLogger();
JSch.setLogger(logger);
JSch jsch = new JSch();
Session session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
Properties conf = new Properties();
conf.put("StrictHostKeyChecking", "no");
conf.put("PreferredAuthentications", "keyboard-interactive");
session.setConfig(conf);
session.setTimeout(1500);
UserClass userClass = new UserClass();
userClass.setPassword(ftpPassword);
session.setUserInfo(userClass);
Sftp sftp = new Sftp(session);
String localFile = "xxx";
String remoteTargetDirectory = "xx";
sftp.put(localFile, remoteTargetDirectory);
sftp.close();
}
此处引用了hutool的包 用原生jsch也是一样的
至此完成 认证方式为:keyboard-interactive 本地文件推送至ftp的流程
调试Logger实现
public class MyJschLogger implements com.jcraft.jsch.Logger {
public boolean isEnabled(int level) {
return true;
}
public void log(int level, String msg) {
System.out.println(msg);
}
}