package sftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Vector;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
/**
jsch-0.1.42.jar
* 每天进步一点一点,比昨天比去年多一点就可以了
* 是的,我可以的,我很强,稳住,守住高地,猥琐发育
* 燃鹅,我也有解决不了的问题,休息,周末愉快
* 各方面的压力、问题源于自己的思想
*
* @author ZengWenfeng
* @date 2021.07.31
*/
public class SFTPTest
{
/**
*
*
* @param host
* @param port
* @param username
* @param password
* @return
*/
public ChannelSftp connect(String host, int port, String username, String password)
{
ChannelSftp sftp = null;
try
{
JSch jsch = new JSch();
jsch.getSession(username, host, port);
//
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
//
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect();
//
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("connected ok.");
}
catch (Exception e)
{
e.printStackTrace();
}
//
return sftp;
}
/**
*
*
* @param dir
* @param fileUpload
* @param sftp
*/
public void put(String dir, String fileUpload, ChannelSftp sftp)
{
try
{
sftp.cd(dir);
File file = new File(fileUpload);
sftp.put(new FileInputStream(file), file.getName());
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
*
*
*
* @param dir
* @param fileDownload
* @param saveFile
* @param sftp
*/
public void get(String dir, String fileDownload, String saveFile, ChannelSftp sftp)
{
try
{
sftp.cd(dir);
File file = new File(saveFile);
sftp.get(fileDownload, new FileOutputStream(file));
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
*
*
* @param dir
* @param fileDelete
* @param sftp
*/
public void rm(String dir, String fileDelete, ChannelSftp sftp)
{
try
{
sftp.cd(dir);
sftp.rm(fileDelete);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
*
*
* @param dir
* @param sftp
* @return
* @throws SftpException
*/
public Vector<?> lsFiles(String dir, ChannelSftp sftp) throws SftpException
{
return sftp.ls(dir);
}
/**
* test
*
*
* @param args
*/
public static void main(String[] args)
{
SFTPTest sf = new SFTPTest();
String host = "192.168.10.100";
int port = 22;
String username = "rpa";
String password = "rpa";
String dir = "/RPA";
String fileUpload = "D:\\20210624213911.jpg";
ChannelSftp sftp = sf.connect(host, port, username, password);
sf.put(dir, fileUpload, sftp);
try
{
sftp.cd(dir);
System.out.println("ok!!!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}