需要使用的jar包
Demo2.java
package com.demo;
import java.io.UnsupportedEncodingException;
public class Demo2 {
public static void main(String[] args) throws UnsupportedEncodingException {
String str3 = "java -version";
SFTPUtil util = SFTPUtil.getSFTPUtilInstance("192.168.78.11", 22, "root", "root");
util.execCmd("", "", str3);
}
}
执行结果:
SFTPHandler.java
package com.demo;
import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class SFTPHandler {
private static final Logger log = LoggerFactory.getLogger(SFTPHandler.class);
protected String charset = "UTF-8";
protected String host;
protected int port;
protected String userName;
protected String password;
protected Channel channel = null;
protected ChannelSftp sftp = null;
protected Session sshSession = null;
/**
* 连接sftp服务器
*
* @return
*/
public boolean connect() {
boolean flag = true;
try {
JSch jsch = new JSch();
jsch.getSession(userName, host, port);
sshSession = jsch.getSession(userName, host, port);
sshSession.setPassword(password);
sshSession.setConfig("StrictHostKeyChecking", "no");
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (Exception e) {
log.error("连接错误", e);
flag = false;
}
return flag;
}
/**
* 执行相关的命令
*/
public void execCmd(String src, String dst, String shellCommand) {
System.out.println("==execCmd==src==" + src + "=====dst===" + dst);
// BufferedReader br = new BufferedReader(new
// InputStreamReader(System.in));
// String command = "hadoop fs -put "+src+" "+dst;
// BufferedReader reader = null;
// 建立服务器连接
if (connect()) {
try {
// 创建sftp通信通道
channel = sshSession.openChannel("shell");
channel.connect(1000);
// 获取输入流和输出流
InputStream instream = channel.getInputStream();
OutputStream outstream = channel.getOutputStream();
PrintWriter printWriter = new PrintWriter(outstream);
System.out.println("准备开始执行了 ===========");
// 发送需要执行的SHELL命令,需要用\n结尾,表示回车
System.out.println("执行命令:" + shellCommand);
printWriter.println(shellCommand);
// 加上个就是为了,结束本次交互
printWriter.println("exit");
printWriter.flush();
System.out.println("执行结束了 ===========");
// 获取命令执行的结果
BufferedReader in = new BufferedReader(new InputStreamReader(instream));
String msg = null;
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
in.close();
outstream.close();
instream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
sshSession.disconnect();
channel.disconnect();
}
}
}
/**
* 上传文件
*
* @param directory
* 上传的服务器目录
* @param inputStream
* 要上传的文件
* @param targetFileName
* 目标文件名
*/
public void upload(String directory, InputStream inputStream, String targetFileName) {
try {
if (connect()) {
sftp.cd(directory);
sftp.put(inputStream, targetFileName);
sftp.setFilenameEncoding("UTF-8");
log.debug("成功上传文件至" + directory);
}
} catch (Exception e) {
log.error("上传错误", e);
} finally {
disconnect();
}
}
/**
*
* 数据导入文件上传
*
* @throws IOException
*
*
*/
public void uploadTxt(String directory, BufferedReader br, String targetFileName) throws IOException {
try {
if (connect()) {
System.out.println("进来了 。。。。");
System.out.println("targetFileName====" + targetFileName);
System.out.println("directory=====" + directory);
sftp.cd(directory);
OutputStream out = sftp.put(targetFileName);
// FileOutputStream fos = (FileOutputStream)
// sftp.put(targetFileName);;
// OutputStreamWriter wr = new OutputStreamWriter(fos, "UTF-8");
sftp.setFilenameEncoding("UTF-8");
String string = "";
while ((string = br.readLine()) != null) {
byte[] b = string.getBytes(StandardCharsets.UTF_8);
out.write(b);
out.flush();
}
out.close();
System.out.println("结束。。。。");
}
} catch (SftpException e) {
e.printStackTrace();
}
}
/**
* 上传文件
*
* @param directory
* 上传的目录
* @param uploadFile
* 要上传的文件
*/
public void upload(String directory, String uploadFile) {
try {
if (connect()) {
sftp.cd(directory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
log.debug("成功上传文件至" + directory);
}
} catch (Exception e) {
log.error("上传错误", e);
} finally {
disconnect();
}
}
/**
* 上传文件
*
* @param directory
* 上传的目录
*/
public void upload(String directory, String fileName, InputStream is) {
try {
if (connect()) {
sftp.cd(directory);
sftp.put(is, fileName);
log.debug("成功上传文件至" + directory);
}
} catch (Exception e) {
log.error("上传错误", e);
} finally {
disconnect();
}
}
/**
* 下载文件
*
* @param directory
* 下载目录
* @param downloadFile
* 下载的文件
* @param saveFile
* 存在本地的路径
*/
public void download(String directory, String downloadFile, String saveFile) {
try {
if (connect()) {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
log.debug("成功下载文件至" + directory);
}
} catch (Exception e) {
log.error("下载错误", e);
} finally {
disconnect();
}
}
/**
* 删除文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
*/
public boolean delete(String directory, String deleteFile) {
boolean flag = true;
try {
if (connect()) {
sftp.cd(directory);
sftp.rm(deleteFile);
log.debug("成功删除文件" + deleteFile);
} else {
flag = false;
}
} catch (Exception e) {
log.error("删除错误", e);
flag = false;
} finally {
disconnect();
}
return flag;
}
/**
* 列出目录下的文件
*
* @param directory
* 要列出的目录
* @return
* @throws SftpException
*/
public Vector listFiles(String directory) {
Vector v = new Vector();
try {
if (connect()) {
v = sftp.ls(directory);
}
} catch (SftpException e) {
log.error("目录查询错误", e);
} finally {
disconnect();
}
return v;
}
/**
* 列出目录下的子目录
*
* @param directory
* 要列出的目录
* @return
* @throws SftpException
*/
public List<String> listDir(String directory) {
Vector v = new Vector();
List<String> dirList = new ArrayList<String>();
try {
if (connect()) {
v = sftp.ls(directory);
for (int i = 0; i < v.size(); i++) {
LsEntry entry = (LsEntry) v.get(i);
String fileName = entry.getFilename();
if (entry.getAttrs().isDir() && !fileName.startsWith(".")) {
dirList.add(fileName);
}
}
}
} catch (SftpException e) {
log.error("目录查询错误", e);
} finally {
disconnect();
}
return dirList;
}
/**
* 关闭连接 server
*/
public void disconnect() {
if (channel != null) {
if (channel.isConnected()) {
channel.disconnect();
log.debug("channel连接关闭成功!" + sftp);
} else if (channel.isClosed()) {
log.info("channel 已经关闭,不需要重复关闭!" + sftp);
}
}
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
log.debug("sftp连接关闭成功!" + sftp);
} else if (sftp.isClosed()) {
log.info("sftp 已经关闭,不需要重复关闭!" + sftp);
}
}
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
log.debug("sshSession连接关闭成功!" + sftp);
}
}
}
public Map<String, String> isConnect() {
Map<String, String> result = new HashMap<String, String>();
try {
if (connect()) {
result.put("isSuccess", "1");
result.put("message", "连接成功!");
} else {
result.put("isSuccess", "0");
result.put("message", "连接失败!");
}
} catch (Exception e) {
result.put("isSuccess", "0");
result.put("message", "连接失败!");
} finally {
disconnect();
}
return result;
}
}
SFTPUtil.java
package com.demo;
public class SFTPUtil extends SFTPHandler {
public static SFTPUtil sftpUtil = null;
public SFTPUtil(String host, int port, String userName, String password) {
this.host = host;
this.port = port;
this.userName = userName;
this.password = password;
}
/**
* 获取sftp
* @param host
* @param port
* @param userName
* @param password
* @return
*/
public static SFTPUtil getSFTPUtilInstance(String host, int port, String userName, String password) {
//多线程同步单例模式
synchronized (SFTPUtil.class) {
sftpUtil = new SFTPUtil(host,port,userName,password);
}
return sftpUtil;
}
}