使用Java的SFTP文件传输JSch
问题描述:
这里是我的代码,它在远程服务器上检索文件的内容并显示为输出。使用Java的SFTP文件传输JSch
package sshexample;
import com.jcraft.jsch.*;
import java.io.*;
public class SSHexample
{
public static void main(String[] args)
{
String user = "user";
String password = "password";
String host = "192.168.100.103";
int port=22;
String remoteFile="sample.txt";
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
System.out.println("Creating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
System.out.println("SFTP Channel created.");
InputStream out= null;
out= sftpChannel.get(remoteFile);
BufferedReader br = new BufferedReader(new InputStreamReader(out));
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
br.close();
sftpChannel.disconnect();
session.disconnect();
}
catch(JSchException | SftpException | IOException e)
{
System.out.println(e);
}
}
}
现在如何实施这一计划,该文件在本地主机以及如何将文件从本地主机到服务器的复制拷贝。
这里如何使工作的文件传输的任何格式的文件。
答
用法:
sftp("file:/C:/home/file.txt", "ssh://user:[email protected]/home");
sftp("ssh://user:[email protected]/home/file.txt", "file:/C:/home");
答
可以通过SFTP上传文件JSch最微不足道的方法是:
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");
类似地,对于下载:
sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");
我提供了一个如何从本地服务器到远程AWS EC2实例执行此操作的示例http://stackoverflow.com/a/16626635/311525 – Scott 2013-09-17 17:20:58
如果您正在寻找本地和远程服务器之间的文件传输,这些链接应该会有所帮助 - [文件上传](http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/),[文件下载](http://kodehelp.com/ Java的程序进行,下载文件,从-SFTP服务器/) – 2013-02-27 23:22:46