/**
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
* @return
* @throws Exception
*/
public static ChannelSftp connect(String host, int port, String username, String password) throws Exception {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (Exception e) {
throw new Exception("连接sftp服务器异常" + e.getMessage(), e);
}
return sftp;
}
/**
* @param directory 上传的服务器目录
* @param uploadFile 要上传的文件流
* @param sftp
* @throws Exception
*/
// public static void upload(String directory, String uploadFile, ChannelSftp sftp) throws Exception {
//
// uploadRename(directory, uploadFile, null, sftp);
// }
public static void upload(String directory, InputStream uploadFile, String fileName, ChannelSftp sftp) throws Exception {
uploadFile(directory, uploadFile, fileName, sftp);
}
public static void uploadFiles(String directory, File file, ChannelSftp sftp) throws Exception {
InputStream in = null;
try {
if (file.isDirectory()) {
sftp.cd(directory);
File[] files = file.listFiles();
for (File f : files) {
in = new FileInputStream(f);
sftp.put(in, f.getName());
}
}
} catch (SftpException | FileNotFoundException e) {
throw new Exception("上传文件异常" + e.getMessage(), e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
throw new Exception("关闭inputStream流异常" + e.getMessage(), e);
}
}
}
/**
* @param directory 上传的目录
* @param uploadFile 要上传的文件
* @param rename 重命名
* @param sftp
* @throws Exception
*/
public static void uploadRename(String directory, String uploadFile, String rename, ChannelSftp sftp)
throws Exception {
InputStream in = null;
try {
mkDir(directory, sftp);
sftp.cd(directory);
File file = new File(uploadFile);
in = new FileInputStream(file);
sftp.put(in, StringUtils.i
sftp工具类
最新推荐文章于 2024-09-12 18:13:34 发布
本文介绍如何利用SSH协议的SFTP子系统进行安全的文件传输,包括连接服务器、上传下载文件及目录操作,是运维工作中常用的一种远程文件管理方式。
摘要由CSDN通过智能技术生成