Ich versuche, eine Datei von einem Server mithilfe von SFTP (im Gegensatz zu FTPS) mithilfe von Java abrufen. Wie kann ich das machen?Wie kann eine Datei von einem Server über SFTP abgerufen werden?
Antwort
Eine weitere Möglichkeit zu prüfen, ist am JSch library suchen. JSch scheint die bevorzugte Bibliothek für einige große Open-Source-Projekte zu sein, darunter Eclipse, Ant und Apache Commons HttpClient.
Es unterstützt sowohl Benutzer/Pass-und Zertifikat-basierte Logins schön, sowie alle eine ganze Reihe von anderen leckeren SSH2-Funktionen.
Hier ist eine einfache Remote-Datei abrufen über SFTP. Die Fehlerbehandlung wird den Leser als Übung überlassen :-)
JSch jsch = new JSch();
String knownHostsFilename = "/home/username/.ssh/known_hosts";
jsch.setKnownHosts(knownHostsFilename);
Session session = jsch.getSession("remote-username", "remote-host");
{
// "interactive" version
// can selectively update specified known_hosts file
// need to implement UserInfo interface
// MyUserInfo is a swing implementation provided in
// examples/Sftp.java in the JSch dist
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
// OR non-interactive version. Relies in host key being in known-hosts file
session.setPassword("remote-password");
}
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get("remote-file", "local-file");
// OR
InputStream in = sftpChannel.get("remote-file");
// process inputstream as needed
sftpChannel.exit();
session.disconnect();
Dies war die Lösung, die ich mit http://sourceforge.net/projects/sshtools/ (die meisten Fehlerbehandlung zur Verdeutlichung weggelassen) kam. Dies ist ein Auszug aus my blog
SshClient ssh = new SshClient();
ssh.connect(host, port);
//Authenticate
PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername(userName);
passwordAuthenticationClient.setPassword(password);
int result = ssh.authenticate(passwordAuthenticationClient);
if(result != AuthenticationProtocolState.COMPLETE){
throw new SFTPException("Login to " + host + ":" + port + " " + userName + "/" + password + " failed");
}
//Open the SFTP channel
SftpClient client = ssh.openSftpClient();
//Send the file
client.put(filePath);
//disconnect
client.quit();
ssh.disconnect();
j2ssh ist ziemlich buggy –
Ich stimme zu (später), es funktionierte gut für die ursprüngliche Seite/Download, die ich benötigte, aber es refused, um für das neue zu arbeiten. Ich bin dabei, zu JSch zu wechseln –
Eine schöne Abstraktion oben auf JSch ist Apache commons-vfs, die einen virtuellen Dateisystem-API bietet, die den Zugriff auf und das Schreiben SFTP machen Dateien fast transparent. Arbeitete gut für uns.
ist es möglich Pre-Shared Keys in Kombination mit Commons-VFS zu verwenden? –
Ja ist es. Wenn Sie nicht standardmäßige Identitäten benötigen, können Sie SftpFileSystemConfigBuilder.getInstance(). SetIdentities (...) aufrufen. –
Sie können vorinstallierte Schlüssel verwenden. Aber diese Schlüssel müssen ohne Passwort sein. OtrosLogViewer verwendet die SSH-Schlüsselautorisierung mit VFS, erfordert jedoch das Entfernen der Passphrase vom Schlüssel (http://code.google.com/p/otroslogviewer/wiki/SftpAuthPubKey) – KrzyH
Die beste Lösung, die ich gefunden habe, ist Paramiko. Es gibt eine Java-Version.
http://www.lag.net/jaramiko/ last updated 12 -Nov-2007; ( –
https://github.com/tenerenhonles/jaramiko wird zugunsten von JSch aufgegeben (siehe Hinweis auf github). –
Sie haben auch JFileUpload mit SFTP Add-on (Java auch): http://www.jfileupload.com/products/sftp/index.html
JFileUpload ist ein Applet, keine lib. Die Lizenz ist kommerziell. Sieht nicht aktiv aus –
Versuchen edtFTPj/PRO, eine ausgereifte, robuste SFTP-Client-Bibliothek, die Verbindungspools und asynchrone Operationen unterstützt. Unterstützt auch FTP und FTPS, so dass alle Grundlagen für den sicheren Dateitransfer abgedeckt sind.
Und bitte erwähnen Sie auch, dass diese Bibliothek bezahlt und nicht frei ist .... – oneConsciousness
Ich benutze diese SFTP-API namens Zehon, es ist großartig, so einfach zu verwenden mit viel Beispielcode. Hier ist die Website http://www.zehon.com
Zehon scheint tot. Und wo ist die Quelle? Was "Lizenz" ist hinter "frei"? –
hierynomus/sshj hat eine vollständige Implementierung von SFTP Version 3 (was OpenSSH implementiert)
Beispielcode von SFTPUpload.java
package net.schmizz.sshj.examples;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;
import java.io.File;
import java.io.IOException;
/** This example demonstrates uploading of a file over SFTP to the SSH server. */
public class SFTPUpload {
public static void main(String[] args)
throws IOException {
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("localhost");
try {
ssh.authPublickey(System.getProperty("user.name"));
final String src = System.getProperty("user.home") + File.separator + "test_file";
final SFTPClient sftp = ssh.newSFTPClient();
try {
sftp.put(new FileSystemFile(src), "/tmp");
} finally {
sftp.close();
}
} finally {
ssh.disconnect();
}
}
}
nice job !! ein Beispiel in der Hauptsache Seite könnte aber hilfreich sein .. – OhadR
Im Folgenden wird ein Beispiel unter Verwendung von Apache Commons VFS:
FileSystemOptions fsOptions = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
FileSystemManager fsManager = VFS.getManager();
String uri = "sftp://user:[email protected]:port/absolute-path";
FileObject fo = fsManager.resolveFile(uri, fsOptions);
Eine andere nette Sache zu tun ist, um die Zeitüberschreitung einzustellen, so dass, wenn das Remote-System offline ist, Sie nicht dort für immer hängen.Sie können dies tun, wie für den Host-Key-Check getan wurde disable: SftpFileSystemConfigBuilder.getInstance(). setTimeout (fsOptions, 5000); –
Wie empfehlen Sie, diese Verbindung zu schließen, wenn Sie mehrere SFTP-Clients gleichzeitig verwenden? – 2Big2BeSmall
Was passiert, wenn mein Passwort @ Symbol enthält? – User3
Hier ist der vollständige Quellcode eines Beispiels mit JSch ohne sich um die Überprüfung der SSH-Schlüssel kümmern.
import com.jcraft.jsch.*;
public class TestJSch {
public static void main(String args[]) {
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("username", "127.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get("remotefile.txt", "localfile.txt");
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
}
}
Ein 'finally'-Block sollte verwendet werden, um den Kanalbereinigungscode aufzunehmen, um sicherzustellen, dass er immer ausgeführt wird. – hotshot309
Ich bekomme diese Ausnahme jetzt: '' 'com.jcraft.jsch.JSchException: Session.connect: java.security.InvalidAlgorithmParameterException: Prime-Größe muss ein Vielfaches von 64 sein, und kann nur zwischen 512 und 2048 (einschließlich) '' ' – anon58192932
fand ich komplett funktionierendes Beispiel für SFTP in java JSch API http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/
Andy verwenden, Datei auf dem Remote-System, das Sie (channelExec)
von JSch verwenden müssen, zu löschen und Unix/Linux-Befehle es passieren zu löschen.
Obwohl die obigen Antworten sehr hilfreich waren, habe ich einen Tag damit verbracht, sie zum Laufen zu bringen, mit verschiedenen Ausnahmen wie "defekter Kanal", "rsa key unknown" und "packet corrupt".
Unten ist eine funktionierende wiederverwendbare Klasse für SFTP FILES UPLOAD/DOWNLOAD mit JSch Bibliothek.
hochladen Nutzung:
SFTPFileCopy upload = new SFTPFileCopy(true, /path/to/sourcefile.png", /path/to/destinationfile.png");
Download-Nutzung:
SFTPFileCopy download = new SFTPFileCopy(false, "/path/to/sourcefile.png", "/path/to/destinationfile.png");
Der Klassencode:
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JOptionPane;
import menue.Menue;
public class SFTPFileCopy1 {
public SFTPFileCopy1(boolean upload, String sourcePath, String destPath) throws FileNotFoundException, IOException {
Session session = null;
Channel channel = null;
ChannelSftp sftpChannel = null;
try {
JSch jsch = new JSch();
//jsch.setKnownHosts("/home/user/.putty/sshhostkeys");
session = jsch.getSession("login", "mysite.com", 22);
session.setPassword("password");
UserInfo ui = new MyUserInfo() {
public void showMessage(String message) {
JOptionPane.showMessageDialog(null, message);
}
public boolean promptYesNo(String message) {
Object[] options = {"yes", "no"};
int foo = JOptionPane.showOptionDialog(null,
message,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo == 0;
}
};
session.setUserInfo(ui);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
sftpChannel = (ChannelSftp) channel;
if (upload) { // File upload.
byte[] bufr = new byte[(int) new File(sourcePath).length()];
FileInputStream fis = new FileInputStream(new File(sourcePath));
fis.read(bufr);
ByteArrayInputStream fileStream = new ByteArrayInputStream(bufr);
sftpChannel.put(fileStream, destPath);
fileStream.close();
} else { // File download.
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));
OutputStream os = new FileOutputStream(new File(destPath));
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
while ((readCount = bis.read(buffer)) > 0) {
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
}
} catch (Exception e) {
System.out.println(e);
} finally {
if (sftpChannel != null) {
sftpChannel.exit();
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive {
public String getPassword() {
return null;
}
public boolean promptYesNo(String str) {
return false;
}
public String getPassphrase() {
return null;
}
public boolean promptPassphrase(String message) {
return false;
}
public boolean promptPassword(String message) {
return false;
}
public void showMessage(String message) {
}
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo) {
return null;
}
}
}
Apache Commons SFTP-Bibliothek
gemeinsame Java-Properties-Datei für alle Beispiele
server = 111.222.333.444
userId = myuserid
Passwort = myPassword
remoteDirectory = products/
localDirectory = Import/
Datei hochladen zu Remote-Server SFTP
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
public class SendMyFiles {
static Properties props;
public static void main(String[] args) {
SendMyFiles sendMyFiles = new SendMyFiles();
if (args.length < 1)
{
System.err.println("Usage: java " + sendMyFiles.getClass().getName()+
" Properties_file File_To_FTP ");
System.exit(1);
}
String propertiesFile = args[0].trim();
String fileToFTP = args[1].trim();
sendMyFiles.startFTP(propertiesFile, fileToFTP);
}
public boolean startFTP(String propertiesFilename, String fileToFTP){
props = new Properties();
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
props.load(new FileInputStream("properties/" + propertiesFilename));
String serverAddress = props.getProperty("serverAddress").trim();
String userId = props.getProperty("userId").trim();
String password = props.getProperty("password").trim();
String remoteDirectory = props.getProperty("remoteDirectory").trim();
String localDirectory = props.getProperty("localDirectory").trim();
//check if the file exists
String filepath = localDirectory + fileToFTP;
File file = new File(filepath);
if (!file.exists())
throw new RuntimeException("Error. Local file not found");
//Initializes the file manager
manager.init();
//Setup our SFTP configuration
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
//Create the SFTP URI using the host name, userid, password, remote path and file name
String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" +
remoteDirectory + fileToFTP;
// Create local file object
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
// Copy local file to sftp server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
System.out.println("File upload successful");
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
finally {
manager.close();
}
return true;
}
}
Datei herunterladen von Remote-Server mit SFTP
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
public class GetMyFiles {
static Properties props;
public static void main(String[] args) {
GetMyFiles getMyFiles = new GetMyFiles();
if (args.length < 1)
{
System.err.println("Usage: java " + getMyFiles.getClass().getName()+
" Properties_filename File_To_Download ");
System.exit(1);
}
String propertiesFilename = args[0].trim();
String fileToDownload = args[1].trim();
getMyFiles.startFTP(propertiesFilename, fileToDownload);
}
public boolean startFTP(String propertiesFilename, String fileToDownload){
props = new Properties();
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
props.load(new FileInputStream("properties/" + propertiesFilename));
String serverAddress = props.getProperty("serverAddress").trim();
String userId = props.getProperty("userId").trim();
String password = props.getProperty("password").trim();
String remoteDirectory = props.getProperty("remoteDirectory").trim();
String localDirectory = props.getProperty("localDirectory").trim();
//Initializes the file manager
manager.init();
//Setup our SFTP configuration
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
//Create the SFTP URI using the host name, userid, password, remote path and file name
String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" +
remoteDirectory + fileToDownload;
// Create local file object
String filepath = localDirectory + fileToDownload;
File file = new File(filepath);
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
// Copy local file to sftp server
localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
System.out.println("File download successful");
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
finally {
manager.close();
}
return true;
}
}
Löschen einer Datei auf dem Remote-Server mit SFTP
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
public class DeleteRemoteFile {
static Properties props;
public static void main(String[] args) {
DeleteRemoteFile getMyFiles = new DeleteRemoteFile();
if (args.length < 1)
{
System.err.println("Usage: java " + getMyFiles.getClass().getName()+
" Properties_filename File_To_Delete ");
System.exit(1);
}
String propertiesFilename = args[0].trim();
String fileToDownload = args[1].trim();
getMyFiles.startFTP(propertiesFilename, fileToDownload);
}
public boolean startFTP(String propertiesFilename, String fileToDownload){
props = new Properties();
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
props.load(new FileInputStream("properties/" + propertiesFilename));
String serverAddress = props.getProperty("serverAddress").trim();
String userId = props.getProperty("userId").trim();
String password = props.getProperty("password").trim();
String remoteDirectory = props.getProperty("remoteDirectory").trim();
//Initializes the file manager
manager.init();
//Setup our SFTP configuration
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
//Create the SFTP URI using the host name, userid, password, remote path and file name
String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" +
remoteDirectory + fileToDownload;
//Create remote file object
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
//Check if the file exists
if(remoteFile.exists()){
remoteFile.delete();
System.out.println("File delete successful");
}
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
finally {
manager.close();
}
return true;
}
}
Quelle: http://www.mysamplecode.com/2013/06/sftp-apache-common-file-download.html –
Sehr nützlicher Code danke @ AZ_ –
, wie man mit ssh-Schlüssel (öffentliches Schlüssel), um Dateien auf dem Server zu kopieren. Weil ich ssh_trust zwischen meinem Server und Remote-Server machen muss. –
Es gibt einen schönen Vergleich der drei reifen Java-Bibliotheken für SFTP: Commons VFS, SSHJ and JSch
Zusammengefasst SSHJ die klarste API hat und es ist das Beste aus ihnen, wenn Sie nicht andere Speicher brauchen unterstützte von Commons VFS. Hier
wird bearbeitet SSHJ Beispiel aus github:
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier())
ssh.connect("localhost");
try {
ssh.authPassword("user", "password"); // or ssh.authPublickey(System.getProperty("user.name"))
final SFTPClient sftp = ssh.newSFTPClient();
try {
sftp.get("test_file", "/tmp/test.tmp");
} finally {
sftp.close();
}
} finally {
ssh.disconnect();
}
JSch Bibliothek ist die leistungsfähige Bibliothek, die verwendet werden kann, Datei von SFTP-Server zu lesen. Im Folgenden finden Sie die getesteten Code-Datei von SFTP Standort Zeile für Zeile
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("user", "127.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
InputStream stream = sftpChannel.get("/usr/home/testfile.txt");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException io) {
System.out.println("Exception occurred during reading file from SFTP server due to " + io.getMessage());
io.getMessage();
} catch (Exception e) {
System.out.println("Exception occurred during reading file from SFTP server due to " + e.getMessage());
e.getMessage();
}
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
Bitte beachten Sie die blog für ganzes Programm zu lesen.
Cheekysoft, Ich bemerkte - während Jsch verwenden - Entfernen von Dateien auf dem SFTP-Server funktioniert nicht. Auch das Umbenennen von Dateien funktioniert nicht. Irgendwelche Ideen bitte ??? Andy –
Sorry, es ist nicht etwas, mit dem ich im Moment arbeite. (Bitte versuchen Sie, diese Art von Antworten als Kommentare zu hinterlassen - wie diese Nachricht - und nicht als neue Antwort auf die ursprüngliche Frage) – Cheekysoft
Was ist dieser Code-Block nach der Zuweisung der Sitzung? Ist das irgendeine ausgefallene Java-Syntax, die ich noch nie gesehen habe? Wenn ja - was bewirkt es, so geschrieben zu sein? –