使用Java JSch进行SFTP文件传输
作者:互联网
这是我的代码,它在远程服务器上检索文件的内容并显示为输出.
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);
}
}
}
现在,如何实现此文件在localhost中复制的程序以及如何将文件从localhost复制到服务器.
这里如何为任何格式的文件传输文件.
解决方法:
使用JSch通过SFTP上传文件的最简单方法是:
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");
你可能需要deal with UnknownHostKey
exception.
标签:jsch,java,sftp,file-transfer,ssh 来源: https://codeday.me/bug/20190923/1814977.html