1 导入pom
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
2 编写配置类
package com.budwk.app.atest;
import com.budwk.app.common.config.AppException;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.nutz.ioc.loader.annotation.IocBean;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@Config
@Slf4j
public class JSchSessionComponent {
private static final String ip = "172.168.1.1";
private static final int port = 22;
private static final String userName = "root";
private static final String password = "123456";
/**
* jsch创建连接
* @return
*/
public Session getJSchSession(){
JSch jSch = new JSch();
Session session = null;
try {
//创建连接
session = jSch.getSession(userName,ip,port);
session.setPassword(password);
//是否使用密钥登录,一般默认为no
session.setConfig("StrictHostKeyChecking", "no");
boolean connected = session.isConnected();
if (connected) {
return session;
}
//启用连接
session.connect(15222200);
log.info("服务器连接成功");
return session;
}catch (Exception e){
log.error("服务器连接失败", e);
throw new AppException("服务器连接失败");
}
}
//jsch关闭连接
public void closeJSchSession(Session session){
log.info("关闭连接开始");
if (session != null) {
session.disconnect();
log.info("关闭连接结束");
}
}
public boolean uploadFile(Session sshSession, File file) {
log.info("文件正在上传中,请等待......");
boolean isSuccess = false;
InputStream is = null;
try {
Channel channel = sshSession.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
sftp.cd("/data/www/wk-mini/");//上传时接文件的服务器的存放目录
String fileName =file.getName();
is = new FileInputStream(file);
sftp.put(is, fileName, ChannelSftp.OVERWRITE);//有重名文件覆盖
log.info("文件上传结束");
isSuccess = true;
} catch (Exception e) {
log.error("linux upload File error:", e);
throw new AppException("文件上传失败");
} finally {
IOUtils.closeQuietly(is);
}
return isSuccess;
}
public List<String> executeShell(Session session , List<String> commands){
log.info("项目开始启动,请等待");
//用来存放命令的返回值
List<String> cmdResult = new ArrayList<>();
for (String command : commands) {
Channel channel = null;
try {
//创建执行通道
channel = session.openChannel("exec");
//设置命令
((ChannelExec) channel).setCommand(command);
//连接通道
channel.connect();
//读取通道的输出
InputStream in = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//存放命令的执行结果,如果结果有很多行,则每次line的值不同
String line;
//lines用来拼接line结果
StringBuffer lines = new StringBuffer();
while ((line = reader.readLine()) != null) {
//去除头尾的空格
line.trim();
lines = lines.append(line);
}
//如果命令执行没有返回值,则直接输出没有返回值
if (String.valueOf(lines).equals("")){
cmdResult.add("命令["+command+"]执行成功,但没有返回值");
}else {
//否则将每行返回直接存入到list中
cmdResult.add(String.valueOf(lines));
}
reader.close();
channel.disconnect();
} catch (Exception e) {
log.error("启动失败", e);
throw new AppException("启动失败");
}
}
log.info("项目启动已结束..................");
return cmdResult;
}
}
3 测试
package com.budwk.app.atest;
import com.jcraft.jsch.*;
import org.nutz.ioc.loader.annotation.IocBean;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@IocBean
public class TestDemo {
public static void main(String[] args) {
// 1 先建立连接
JSchSessionComponent jSchSessionComponent = new JSchSessionComponent();
Session session = jSchSessionComponent.getJSchSession();
File file = new File("E:\\target\\111.jar");
// File file = new File("E:\\target\\1.txt");
boolean b = jSchSessionComponent.uploadFile(session, file);
if (b) {
System.out.println("文件上传成功");
}
jSchSessionComponent.closeJSchSession(session);
// TestDemo t = new TestDemo();
// t.executeSheel();
}
private void executeSheel() {
JSchSessionComponent jSchSessionComponent = new JSchSessionComponent();
Session session = jSchSessionComponent.getJSchSession();
// 执行命令
List<String> cmds = new ArrayList<>();
cmds.add("cd /data/www/;chmod u+x start.sh;./start.sh");
jSchSessionComponent.executeShell(session, cmds);
}
//用来执行命令
//Session表示传递连接对话,commands表示传递命令集合
}
4 start.sh文件内容体
# sh ./monitorstart.sh
# sh ./jobstart.sh
#!/bin/sh
RESOURCE_NAME=wkProject.jar
tpid=`ps -ef|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
echo 'Stop Process...'
kill -15 $tpid
fi
sleep 5
tpid=`ps -ef|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
echo 'Kill Process!'
kill -9 $tpid
else
echo 'Stop Success!'
fi
tpid=`ps -ef|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
echo 'App is running.'
else
echo 'App is NOT running.'
fi
rm -f tpid
rm -f wkProject.log
nohup java -jar ./$RESOURCE_NAME >>wkProject.log 2>&1 &
echo $! > tpid
echo Start Success!