1.导包
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
2.ssh协议远程登录服务器
import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.List;
import java.util.Properties;
@Component
public class JSchSession {
private Channel channel= null;
private ChannelShell channelShell = null;
private Session session = null;
private int timeout = 60000;
//建立连接
public boolean getConnect() throws JSchException {
//创建JSch对象
JSch jSch = new JSch();
//根据用户名,主机ip和端口获取一个Session对象
session = jSch.getSession("root", "192.168.128.41", 22);
//设置密码
session.setPassword("123456");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
//为Session对象设置properties
session.setConfig(config);
//设置超时
session.setTimeout(timeout);
//通过Session建立连接
session.connect();
if (session.isConnected()) {
return true;
}else {
return false;
}
}
}
3.sftp上传脚本文件,下面的sftpChannel使用上面的sftpChannel,目标路径应该做自动创建目录的,可以自己加,这是我在做功能时测试用的,所以没加,对于异常,建议加在里面捕获处理,不要抛出。
//上传文件至目标服务器
public boolean Uploadserver() throws Exception {
sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
String src = "C:\\Users\\Administrator\\Desktop\\ys.sh"; // 本地文件名
String dst = "/home/upload"; // 目标文件名
sftpChannel.put(src,dst);
return true;
}
4.执行命令,由于业务需要,我做了两个接口,一个命令执行,一个脚本执行,后面上代码
public boolean CommandExecution() throws Exception {
channelShell = (ChannelShell) session.openChannel("shell");//使用xhell操作ftpc,exec
channelShell.connect();//建立连接
InputStream inputStream = channelShell.getInputStream();//从远端读取数据
OutputStream outputStream = channelShell.getOutputStream();//发送到远端
String cmd3 = "cd /root/xrjtest";
printWriter.println(cmd3);
printWriter.println("exit");//加上个就是为了,结束本次交互
printWriter.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String msg = null;
while((msg = in.readLine())!=null){
System.out.println(msg);
}
in.close();
return true;
}
5.调用脚本,第一个参数是脚本名,第二个参数是脚本带的参数,此处默认带一个参数,博主正在解决一个接口处理多种类型脚本,实现自动匹配参数个数,参数位置。
public boolean ScriptExecution(String scriptName,String parameter){
try{
channel = session.openChannel("exec");
ChannelExec execChannel = (ChannelExec)channel;
execChannel.setCommand("bash /home/upload/"+scriptName+" "+parameter);
channel.connect();
InputStream inputStream = channel.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedInputStream in = new BufferedInputStream(inputStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String c = null;
while ((c = br.readLine()) != null) {
sb.append(c);
}
System.out.println("执行结果:\n"+sb.toString());
in.close();
}catch (JSchException e) {
e.printStackTrace();
return false;
}catch (IOException e) {
e.printStackTrace();
} finally{
channel.disconnect();
session.disconnect();
}
return true;
}