/**
* Sftp连接类
*
* @author:Lichangjiang
* @date:2020/10/20 9:23
*/
public class SFTPUtil {
private static final Logger log = Logger.getLogger(SFTPUtil.class);
//主机地址
private static String host = "10.2.12.73";
//端口号
private static int post = 22;
//登录用户名
private static String username = "root";
//登录密码
private static String password = "123456";
/**
* 连接sftp服务器
*
* @param host 服务器地址
* @param port 服务器端口
* @param username 登录用户名
* @param password 登录密码
* @return
*/
public static ChannelSftp connect(String host, int port, String username, String password) {
ChannelSftp sftp = null;
Session session = null;
try {
long start = System.currentTimeMillis();
JSch jsch = new JSch();
//创建session,并将用户名,主机地址以及端口号放入到session中
session = jsch.getSession(username, host, port);
System.out.println("创建Session!");
//设置密码
session.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
//创建连接
session.connect();
System.out.println("session连接");
//打开channel
Channel channel = session.openChannel("sftp");
channel.connect();
long end = System.currentTimeMillis();
sftp = (ChannelSftp) channel;
System.out.println("成功连接到" + host);
System.out.println("成功登陆sftp,登陆耗时:[" + (end - start) + "]毫秒");
//获取指定目录下的所有文件
sftp.cd("/home/java/test");
Vector<ChannelSftp.LsEntry> list = sftp.ls("*.csv");
for (ChannelSftp.LsEntry entry : list) {
System.out.println(entry.getFilename());
}
} catch (Exception e) {
log.error("sftp连接失败:", e);
} finally {
//关闭session
if (session!=null){
session.disconnect();
}
//关闭sftp
if (sftp!=null){
sftp.disconnect();
}
}
return sftp;
}
//启动测试
public static void main(String[] args) {
ChannelSftp sftp = connect(host, post, username, password);
System.out.println(sftp);
}