1、依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.49</version>
</dependency>
<dependency>
<groupId>com.trilead</groupId>
<artifactId>trilead-ssh2</artifactId>
<version>1.0.0-build222</version>
</dependency>
2、代码
/**
* sftp上传单个文件
*
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
* @param directory 上传的目录
* @param uploadFile 要上传的文件
* @return
*/
public static boolean sftpUploadFile(String host, int port, String username, String password,String directory, String uploadFile) {
ChannelSftp sftp = null;
Session sshSession=null;
Channel channel=null;
boolean flag=true;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
//LOG.info("SFTP Session connected.");
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
sftp.cd(directory);
File file = new File(uploadFile);
FileInputStream fileInputStream = new FileInputStream(file);
sftp.put(fileInputStream, file.getName());
fileInputStream.close();
System.out.println("上传服务器成功");
} catch (Exception e) {
flag=false;
}finally {
sftp.disconnect();
sshSession.disconnect();
channel.disconnect();
}
return flag;
}