package logSFTP;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class SftpTool
{
private Session session = null;
private ChannelSftp channel = null;
private String sftpUserName;
private String sftpServerIp;
private String sftpPassword;
private int sftpPort;
/**
* 开始连接
*/
public String connected (String serverIp, String userName, String password ,int port)
{
String msg = "";
this.sftpServerIp = serverIp;
this.sftpUserName = userName;
this.sftpPassword = password;
this.sftpPort = port;
JSch jsch = new JSch();
try
{
session = jsch.getSession(this.sftpUserName, this.sftpServerIp, this.sftpPort);
session.setPassword(this.sftpPassword);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(30000);
session.connect();
//打开SFTP通道
channel = (ChannelSftp)session.openChannel("sftp");
channel.connect();
msg = "Success";
}
catch (JSchException e)
{
msg = "登录失败,可能是用户名或密码错误!";
session = null;
}
return msg;
}
/**
* 列出文件
*/
//public
/**
* 下载文件
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
* @param sftp
*/
public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp)
{
try
{
sftp.cd(directory);
File file=new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public String close ()
{
if (channel != null)
{
channel.disconnect();
}
if (session != null)
{
session.disconnect();
}
return "连接断开";
}
}