jschutil这个是改的⽐较好的性能还⾏单例的package utils;
import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import myjschtest.SFTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
/**
* 注释
*
* @Author: coding99
* @Date: 16-9-2
* @Time: 下午7:33
*/
public class JschUtil {
private static final Logger logger = Logger(JschUtil.class);
private String charset = "UTF-8"; // 设置编码格式,可以根据服务器的编码设置相应的编码格式
private JSch jsch;
private Session session;
/*Channel channel = null;
ChannelSftp chSftp = null;
*/
//初始化配置参数
private String jschHost = "192.168.1.105";
private int jschPort = 22;
private String jschUserName = "root";
private String jschPassWord ="yf_05191006";
private int jschTimeOut = 1000*5;
static private JschUtil schutil;
/**
* 静态内部类实现单例模式
*/
/*  private static class LazyHolder {
private static final JschUtil INSTANCE = new JschUtil();
}*/
private JschUtil() {
System.out.print("JschUtil wxq new");
}
/**
* 获取实例
* @return
*/session下载
public static  JschUtil getInstance() {
if(schutil==null) {
schutil=new JschUtil();
System.out.println("new schutil");
}
return schutil;
}
/**
* 连接到指定的服务器
* @return
* @throws JSchException
*/
public boolean connect() throws JSchException {
if(this.session!=null && this.session.isConnected()){
//System.out.println("已经连接不需要在连");
return true;
}
jsch = new JSch();// 创建JSch对象
boolean result = false;
try{
long begin = System.currentTimeMillis();//连接前时间
logger.debug("Try to connect to jschHost = " + jschHost + ",as jschUserName = " + jschUserName + ",as jschPort = " + jschPort);
session = Session(jschUserName, jschHost, jschPort);// // 根据⽤户名,主机ip,端⼝获取⼀个Session对象
session.setPassword(jschPassWord); // 设置密码
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);// 为Session对象设置properties
session.setTimeout(jschTimeOut);//设置连接超时时间
logger.debug("Connected successfully to jschHost = " + jschHost + ",as jschUserName = " + jschUserName + ",as jschPort =  " + jschPort);
long end = System.currentTimeMillis();//连接后时间
logger.debug("Connected To SA Successful in {} ms", (end-begin));
System.out.println("Connected To SA Successful in {} ms"+ (end-begin));
result = session.isConnected();
}catch(Exception e){
System.out.println();
e.printStackTrace();
<(e.getMessage(), e);
}finally{
if(result){
logger.debug("connect success");
}else{
logger.debug("connect failure");
}
}
if(!session.isConnected()) {
<("获取连接失败");
}
return  session.isConnected();
}
/**
* 关闭连接
*/
public void close() {
/
*if(channel != null && channel.isConnected()){
channel.disconnect();
channel=null;
}*/
if(session!=null && session.isConnected()){
session.disconnect();
session=null;
}
}
/**
* 脚本是同步执⾏的⽅式
* 执⾏脚本命令
* @param command
* @return
*/
public Map<String,Object> execCmmmand(String command) throws Exception{        Map<String,Object> mapResult = new HashMap<String,Object>();
logger.debug(command);
StringBuffer result = new StringBuffer();//脚本返回结果
BufferedReader reader = null;
int returnCode = -2;//脚本执⾏退出状态码
try {
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).);
InputStream in = InputStream();
reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
String res="";
while((adLine()) != null){
result.append(res+"\n");
logger.debug(res);
}
returnCode = ExitStatus();
mapResult.put("returnCode",returnCode);
mapResult.put("result",String());
} catch (IOException e) {
<(e.getMessage(),e);
} catch (JSchException e) {
<(e.getMessage(), e);
} finally {
try {
reader.close();
} catch (IOException e) {
<(e.getMessage(), e);
}
}
return mapResult;
}
/**
* 上传⽂件
*
* @param directory 上传的⽬录,有两种写法
*                  1、如/opt,拿到则是默认⽂件名
*                  2、/opt/⽂件名,则是另起⼀个名字
* @param uploadFile 要上传的⽂件 如/
*/
public void upload(String directory, String uploadFile) {
Channel channel=null;
ChannelSftp chSftp=null;
try {
t()==false) {
System.out.println("链接失败wxq");
}
logger.debug("Opening Channel.");
channel = session.openChannel("sftp"); // 打开SFTP通道
chSftp = (ChannelSftp) channel;
File file = new File(uploadFile);
long fileSize = file.length();
/*⽅法⼀*/
OutputStream out = chSftp.put(directory, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); // 使⽤OVERWRITE模式
byte[] buff = new byte[1024 * 256]; // 设定每次传输的数据块⼤⼩为256KB
int read;
if (out != null) {
logger.debug("Start to read input stream");
InputStream is = new FileInputStream(uploadFile);
do {
read = is.read(buff, 0, buff.length);
if (read > 0) {
out.write(buff, 0, read);
}
out.flush();
} while (read >= 0);
logger.debug("input stream read done.");
}
// chSftp.put(uploadFile, directory, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); //⽅法⼆
/
/ chSftp.put(new FileInputStream(src), dst, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); //⽅法三            logger.debug("成功上传⽂件⾄"+directory);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(chSftp!=null)
chSftp.quit();
if (channel != null) {
channel.disconnect();
logger.debug("channel disconnect");
}
}
}
/**
* 下载⽂件
*
* @param directory 下载的⽬录,有两种写法
*                  1、如/opt,拿到则是默认⽂件名
*                  2、/opt/⽂件名,则是另起⼀个名字
* @param downloadFile 要下载的⽂件 如/
*
*/
public void download(String directory, String downloadFile) {
Channel channel=null;
ChannelSftp chSftp=null;
try {

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。