连接另一台服务器的代码如下
/**
* @param host
* 另一台服务器地址
* @param port
* 另一台服务器端口
* @param username
* 另一台服务器权限账户用户名
* @param password
* 另一台服务器权限账户密码
* @return
*/
public ChannelSftp connect(String host, int port, String username, String password) {
ChannelSftp sftp = null;
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;
return sftp;
}
将本地服务器上的文件传送至另一台服务器代码如下
/**
* 文件上传
*
* @param directory 上传至另一台服务器的存储路径
* @param uploadFile 本服务器需要上传的文件路径及文件名
* @param sftp 调用上方连接另一台服务器的方法connect
*/
public void SendFile(String directory, String uploadFile, ChannelSftp sftp) {
sftp.cd(directory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
}
从另一台服务器上传送文件至本地服务器代码
/**
* 文件下载
*
* @param directory 另一台服务器的存储路径
* @param downloadFile 要下载的文件路径及文件名
* @param saveFile 下载下来的文件名(如下载到本地服务器需要更改文件名)
* @param sftp 调用上方连接另一台服务器的方法connect
*/
public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
}
原文链接:https://blog.csdn.net/weixin_42827898/article/details/114342549