SFTP FTPS
Voir également les classes src/main/java/ch/lepag/transport_appl/backup/ServerFtpBackup.java
SFTP
Connexion et update
Maven
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
Java
package ch.lepag.packageutils;
import com.jcraft.jsch.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Upload Files to SFTP Server
* args[0] = full path to msi file
* args[1] = full path to xml latestupdatefile
*
* For test:
* args[0] = "C:/Users/pag/IdeaProjects/FPerrinTransport_Project/FPerrin_transport_Projet/deployement/FPerrin Gestion transport-3.1.12.msi";
* args[1] = "D:/workspacePHP/perrin-transport.ch/update_zip_file/latestUpdatedFile.xml";
*
*/
public class UploadToServer {
private String remoteHost = "mhtf.ftp.infomaniak.com";
private String username = "mhtf_pag";
private String password = "kainamofni_67";
// read password from file
private Session jschSession;
private ChannelSftp channelSftp;
public static void main(String[] args) {
if(args.length == 0){
System.out.println("No path to msi file");
System.exit(0);
}
if(args.length == 1){
System.out.println("No path to latest update file");
System.exit(0);
}
String pathMsi= args[0];
String pathLatestUpdatefile = args[1];
UploadToServer server = new UploadToServer();
try {
server.connect();
//server.send(pathMsi, "gestion_perrin_transport_update.msi");
//server.send(pathLatestUpdatefile, "latestUpdatedFile.xml");
server.get();
server.disconnect();
} catch (IOException | SftpException | JSchException e) {
e.printStackTrace();
try {
server.disconnect();
} catch (JSchException ex) {
throw new RuntimeException(ex);
}
} finally {
System.exit(0);
}
}
private ChannelSftp setupJsch() throws JSchException, IOException {
JSch jsch = new JSch();
// si le serveur n'est pas dans le known_hosts
// ssh-keyscan -H -t rsa REMOTE_HOSTNAME >> C:/Users/pag/.ssh/known_hosts/known_hosts
//jsch.setKnownHosts("C:/Users/pag/.ssh/known_hosts");
// autrement ci dessous le fait automatiquement
jschSession.setConfig("StrictHostKeyChecking", "no");
jschSession = jsch.getSession(username, remoteHost);
String password = Files.readString(Paths.get("C:/Users/pag/IdeaProjects/FPerrinTransport_Project/FPerrin_transport_Projet/travail/password.txt"));
jschSession.setPassword(password);
jschSession.connect();
return (ChannelSftp) jschSession.openChannel("sftp");
}
public void connect() throws JSchException, IOException {
channelSftp = setupJsch();
channelSftp.connect();
}
public void disconnect() throws JSchException {
channelSftp.exit();
jschSession.disconnect();
}
public void send(String pathMsi, String uploadedFileName) throws IOException, SftpException, JSchException {
String localFile = pathMsi; // "C:/Users/pag/IdeaProjects/FPerrinTransport_Project/FPerrin_transport_Projet/deployement/gestion_perrin_transport_update.msi";
String remoteDir = "web/update_zip_file/";
channelSftp.put(localFile, remoteDir + uploadedFileName);
}
public void get() throws SftpException, JSchException, IOException {
String remoteFile = "web/update_zip_file/gestion_perrin_transport_update.msi";
String localDir = "/";
//channelSftp.cd("/web/update_zip_file/");
channelSftp.get(remoteFile, localDir + "aaa.msi", new SystemOutProgressMonitor());
}
Connexion and download
private void downloadSftpFile() throws SftpException, JSchException, IOException {
JSch jsch = new JSch();
final Session jschSession;
final ChannelSftp channelSftp;
jschSession = jsch.getSession(username, remoteHost);
jschSession.setConfig("StrictHostKeyChecking", "no");
//String password = Files.readString(Paths.get("C:/Users/pag/IdeaProjects/FPerrinTransport_Project/FPerrin_transport_Projet/travail/password.txt"));
jschSession.setPassword(password);
jschSession.connect();
channelSftp = (ChannelSftp) jschSession.openChannel("sftp");
String localDir = "/";
//channelSftp.cd("/web/update_zip_file/");
Task<Void> downloadTask = new Task<Void>() {
final String remoteFile = "web/update_zip_file/gestion_perrin_transport_update.msi";
@Override
public Void call() throws MalformedURLException, IOException, SftpException, JSchException {
// si le serveur n'est pas dans le known_hosts
// ssh-keyscan -H -t rsa REMOTE_HOSTNAME >> C:/Users/pag/.ssh/known_hosts/known_hosts
//jsch.setKnownHosts("C:/Users/pag/.ssh/known_hosts");
// autrement ci dessous le fait automatiquement
channelSftp.connect();
channelSftp.get(remoteFile , downloadFolder + File.separator + downloadFileName, new SftpProgressMonitor(){
private long max = 0;
private int done = 0;
private int in = 0;
@Override
public void init(int i, String s, String s1, long l) {
//System.out.println("STARTING: " + i + " " + s + " -> " + s1 + " total: " + l);
max = l;
}
@Override
public boolean count(long l) {
in += (int) l;
for(int x=0; x < l; x++) {
if(x == 0) {
int f = (int) (((double) in / (double) max) * 100);
if (done != f) {
done = f;
updateProgress(done, 100);
}
}
}
return true;
}
@Override
public void end() {
}
});
return null;
}
};
loadProgress.progressProperty().bind(downloadTask.progressProperty());
downloadTask.setOnSucceeded((WorkerStateEvent event) -> {
addText("Téléchargement terminé.");
loadProgress.progressProperty().unbind();
channelSftp.exit();
jschSession.disconnect();
closeAndStartApplication();
});
downloadTask.setOnFailed((WorkerStateEvent event) -> {
final Throwable e = downloadTask.getException();
alert("Une erreur est survenue lors du téléchargement", e);
e.printStackTrace();
channelSftp.exit();
jschSession.disconnect();
});
Thread th = new Thread(downloadTask);
th.setDaemon(true);
th.start();
}
FTPS
Connexion and download
private void downloadFileFtps(){
;
final FTPSClient ftpsClient = new FTPSClient("TLS");
Task<Void> downloadTask = new Task<Void>() {
private long fileSize;
final String fileName ="gestion_perrin_transport_update.msi";
@Override
public Void call() throws IOException {
ftpsClient.connect(remoteHost, 21);
if (ftpsClient.login(username, password)) {
ftpsClient.execPBSZ(0);
ftpsClient.execPROT("P");
// Set binary mode
ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
fileSize = ftpsClient.mlistFile(fileName).getSize();
ftpsClient.enterLocalPassiveMode();
ftpsClient.setCopyStreamListener(new CopyStreamListener() {
private long megsTotal;
@Override
public void bytesTransferred(CopyStreamEvent copyStreamEvent) {}
@Override
public void bytesTransferred(final long totalBytesTransferred, final int bytesTransferred, final long streamSize) {
final long megs = totalBytesTransferred / 1000000;
for (long l = megsTotal; l < megs; l++) {
updateProgress(megs, (fileSize/1000000));
System.err.print("#"+megs);
}
megsTotal = megs;
}
});
try(FileOutputStream fileOutputStream = new FileOutputStream(downloadFolder + File.separator + downloadFileName);
BufferedOutputStream outputStream = new BufferedOutputStream(fileOutputStream)) {
//ftpsClient.changeWorkingDirectory(fileDirectory);
ftpsClient.retrieveFile(fileName, outputStream);
}
}
return null;
};
};
loadProgress.progressProperty().bind(downloadTask.progressProperty());
downloadTask.setOnSucceeded((WorkerStateEvent event) -> {
addText("Téléchargement terminé.");
loadProgress.progressProperty().unbind();
try {
if (ftpsClient.isConnected()) {
ftpsClient.logout();
ftpsClient.disconnect();
}
} catch (IOException ignored) {}
closeAndStartApplication();
});
downloadTask.setOnFailed((WorkerStateEvent event) -> {
final Throwable e = downloadTask.getException();
alert("Une erreur est survenue lors du téléchargement", e);
e.printStackTrace();
try {
if (ftpsClient.isConnected()) {
ftpsClient.logout();
ftpsClient.disconnect();
}
} catch (IOException ignored) {}
});
Thread th = new Thread(downloadTask);
th.setDaemon(true);
th.start();
}