项目中遇到,记录一下。
依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
代码
package com.sptit.isv.utils;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Package: com.sptit.isv.utils
* @ClassName: SSHClient
* @Author: LianKun_Zhang
* @CreateTime: 2020/7/2 13:57
* @Description:
*
* 模拟ssh连接服务器或交换机执行命令读取返回结果
* (未知原因,只能执行一条命令)
*/
public class SSHClient {
/**
* 执行shell命令
* @param session session会话
* @param shell 命令
* @param endShell 退出命令(交换机和服务器不同,exit或quit)
* @return
*/
public static String execCommandByShell(Session session, String shell, String endShell) {
String result = "";
// 2.尝试解决 远程ssh只能执行一句命令的情况
ChannelShell channelShell;
try {
channelShell = (ChannelShell) session.openChannel("shell");
//从远端到达的数据都能从这个流读取到
InputStream inputStream = channelShell.getInputStream();
channelShell.setPty(true);
channelShell.connect();
// 写入该流的数据都将发送到远程端
OutputStream outputStream = channelShell.getOutputStream();
// 使用PrintWriter 就是为了使用println 这个方法好处就是不需要每次手动给字符加\n
PrintWriter printWriter = new PrintWriter(outputStream);
//用的时候发现如果不加延迟,直接执行完会读不到返回结果,不清楚什么原因
Thread.sleep(1000);
printWriter.println(shell);
printWriter.println(endShell);
printWriter.flush();
result = getTemplateContent(inputStream);
outputStream.close();
inputStream.close();
channelShell.disconnect();
session.disconnect();
} catch (JSchException js) {
js.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}
/**
* 根据流读取返回结果
* @param inputStream inp
* @return 执行命令返回结果
*/
public static String getTemplateContent(InputStream inputStream) {
StringBuffer str = new StringBuffer("");
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader in = new BufferedReader(isr);
String line = null;
try {
while ((line = in.readLine()) != null) {
str.append(line + "\r\n");
}
in.close();
} catch (IOException io) {
io.printStackTrace();
}
return str.toString();
}
/**
* 创建一个Session对象(包括登录信息)
* @param userName 用户名
* @param password 密码
* @param IP IP
* @return session
*/
public static Session getSession(String userName, String password, String IP) {
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(userName, IP, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
} catch (JSchException js) {
js.printStackTrace();
}
return session;
}
}
分页问题
如果返回结果是:---- More ---- 结尾,说明还有数据需要翻页查看,但是这部分代码不能模拟空格翻页的操作,
可以修改一下交换机的全局设置,设置成不分页。
(华为交换机为例):
<Huawei> system-view
[Huawei] user-interface vty 0 4
[user-interface vty 0 4] screen-length 0
[user-interface vty 0 4] quit