参考网址:就特么忘记参考的那个网址了,好长时间之前写的
pom.xml添加依赖
com.jcraft
jsch
0.1.53
org.apache.commons
commons-io
1.3.2
ssh连接测试代码:
直接在main方法中调用即可
//查看文件个数
String commond = "ls -lR /share | grep \"^-\" | wc -l";
String ls = SSHUtils.execCommandByJSch(ip, port,user, pwd,commond);
//查看文件大小String fileSize = SSHUtils.execCommandByJSch(ip, port,user, pwd, "du -sm /share |awk '{print $1}'");
ssh连接liunx工具类:
package cn.com.taiji.commons.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
* @desc
* @para
* @author
* @version 2018年6月6日 下午2:39:07
*/
public class SSHUtils {
private static final String ENCODING = "UTF-8";
private static final int timeout = 60 * 60 * 1000;
private static final int defaultPort = 22;
public static Session getJSchSession(String ip,int port,String user,String pwd,int timeout) throws JSchException {
JSch jsch = new JSch();
Session session = jsch.getSession(user, ip, port);
session.setPassword(pwd);
session.setConfig("StrictHostKeyChecking", "no"); // 第一次访问服务器时不用输入yes
session.setTimeout(timeout);
session.connect();
return session;
}
public static String execCommandByJSch(String ip,String user,String pwd,String command) throws IOException, JSchException {
return execCommandByJSch(ip, defaultPort, user, pwd, timeout, command, ENCODING);
}
public static String execCommandByJSch(String ip,int port,String user,String pwd,String command) throws IOException, JSchException {
return execCommandByJSch(ip, port, user, pwd, timeout, command, ENCODING);
}
public static String execCommandByJSch(String ip,int port,String user,String pwd,int timeout, String command, String resultEncoding) throws IOException, JSchException {
Session session = getJSchSession(ip, port, user, pwd, timeout);
String result = execCommandByJSch(session, command, resultEncoding);
session.disconnect();
return result;
}
public static String execCommandByJSch(Session session, String command) throws IOException, JSchException {
return execCommandByJSch(session, command, ENCODING);
}
public static String execCommandByJSch(Session session, String command, String resultEncoding) throws IOException, JSchException {
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.setErrStream(System.err);
channelExec.connect();
String result = IOUtils.toString(in, resultEncoding);
channelExec.disconnect();
return result;
}
}