SshUtil类的ssh相关使用方法
@Slf4j
public class SshUtil {
public static String getSshResult(SshInfo sshInfo) {
InputStream inputStream = null;
String result = null;
log.info("开始连接主机");
log.info("host={};username={};password={};port={}", sshInfo.getHost(), sshInfo.getUsername(), sshInfo.getPassword(), sshInfo.getPort());
log.info("command={}", sshInfo.getCommand());
try {
JSch jsch = new JSch();
Session session = jsch.getSession(sshInfo.getUsername(), sshInfo.getHost(), sshInfo.getPort());
session.setPassword(sshInfo.getPassword());
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshConfig.put("PreferredAuthentications", "password");
session.setConfig(sshConfig);
session.connect();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(sshInfo.getCommand());
channel.setInputStream(null);
channel.setErrStream(System.err);
channel.connect();
inputStream = channel.getInputStream();
result = FileUtil.inputSteamToString(inputStream);
if (!channel.isClosed()) {
channel.disconnect();
}
if (session.isConnected()) {
session.disconnect();
}
log.info("执行命令结束,返回结果为");
log.info(result);
return result;
} catch (JSchException | IOException e) {
e.printStackTrace();
return null;
//throw new LogicException(ErrorcodeEnum.SSH_CONNECTION_ERROR, "主机" + sshInfo.getHost() + "ssh连接失败");
}
}
private static Session getSession(String host, String username, String password, int port) throws JSchException {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect();
return session;
}
public static Session getSession(GenesisNodeConfig nodeConfig) throws JSchException {
return getSession(nodeConfig.getIp(), nodeConfig.getUsername(), nodeConfig.getPassword(), Integer.parseInt(nodeConfig.getPort()));
}
public static Session getSession(K8sMasterConfig1 k8sMaster) throws JSchException {
return getSession(k8sMaster.getIp(), k8sMaster.getUsername(), k8sMaster.getPassword(), Integer.parseInt(k8sMaster.getPort()));
}
public static Session getSession(K8sMasterConfig2 k8sMaster) throws JSchException {
return getSession(k8sMaster.getIp(), k8sMaster.getUsername(), k8sMaster.getPassword(), Integer.parseInt(k8sMaster.getPort()));
}
public static String getResult(Session session, String command) throws IOException, JSchException {
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
channel.connect();
InputStream inputStream = channel.getInputStream();
String result = FileUtil.inputSteamToString(inputStream);
if (!channel.isClosed()) {
channel.disconnect();
}
return result;
}
public static void exec(Session session, String command) throws JSchException, IOException {
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
InputStream in = channel.getInputStream();
InputStream errIn = channel.getErrStream();
channel.setPty(true);
channel.connect();
StringBuilder outBuilder = new StringBuilder();
StringBuilder errBuilder = new StringBuilder();
int exitStatus;
byte[] buf = new byte[1024];
while (true) {
int len = -1;
while ((len = in.read(buf)) != -1) {
outBuilder.append(new String(buf, 0, len));
}
while ((len = errIn.read(buf)) != -1) {
errBuilder.append(new String(buf, 0, len));
}
if (channel.isClosed()) {
if (in.available() > 0 || errIn.available() > 0) continue;
exitStatus = channel.getExitStatus();
break;
}
}
if (errBuilder.length() > 0) {
log.error("jsch执行结果是:\n {}", errBuilder.toString());
}
log.info("jsch执行错误:\n {}", outBuilder.toString());
log.info("命令执行结束,返回状态为 {}", exitStatus);
in.close();
errIn.close();
channel.disconnect();
System.out.println(3);
}
// 当命令中包含重定向 ' < ' ' > ' 和管道符' | ' 时,exec(String command)方法便不适用了,需要使用exec(String [] cmdArray) 或者exec(String []cmdarray,String []envp,File dir)来执行。
// 例如:
// exec("echo hello >> ouput.txt");
// exec("history | grep -i mvn");
// 应改为:
// exec( new String[]{"/bin/sh","-c","echo hello >> ouput.txt"});
// exec( new String[]{"/bin/bash","-c","history | grep -i mvn"},null);
public static boolean runCommand(String[] command) throws IOException, InterruptedException {
log.info("===================执行{}命令开始,开始时间为{}========================", command[command.length - 1], new Date());
Runtime runtime = getRuntime();
Process process = runtime.exec(command);
process.waitFor();
int existValue = process.exitValue();
if (existValue != 0) {
log.error("===================执行{}命令失败.========================", command[command.length - 1]);
return false;
}
log.info("===================执行{}命令结束.========================", command[command.length - 1]);
return true;
}
public static boolean runCommand(String command) throws IOException, InterruptedException {
log.info("===================执行{}命令开始,开始时间为{}========================", command, new Date());
Runtime runtime = getRuntime();
Process process = runtime.exec(command);
process.waitFor();
int existValue = process.exitValue();
if (existValue != 0) {
log.error("===================执行{}命令失败.========================", command);
return false;
}
log.info("===================执行{}命令结束,结束时间为{}========================", command, new Date());
return true;
}
public static void fileDownload(Session session,String src, String dst) throws JSchException, SftpException {
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.get(src, dst);
channelSftp.quit();
}
public static void fileUpload(Session session, File uploadFile, String directory) throws JSchException, SftpException, FileNotFoundException {
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.put(new FileInputStream(uploadFile), directory, ChannelSftp.OVERWRITE);
channelSftp.quit();
}
}
下面有两种使用ssh的方法:(SshUtil即为上面的util类,里面的方法可直接调用)
一.(此方法需要在util类中添加@Builder注解方可使用)
1.声明一个String类型的command(内容为linux命令)
2.声明SshInfo类型的值,用来配置相关的用户名,密码,ip和端口号
SshInfo info = SshInfo.builder().host(ip).username(username).password(password).port(port).command(command).build();`
下面是SshInfo类的内容
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SshInfo {
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 主机地址
*/
private String host;
/**
* 端口
*/
private int port;
/**
* 命令
*/
private String command;
3.用String类型接收返回值
String str = SshUtil.getSshResult(info);
4.可将String类型进行转换
二.(通过传入一个entity类,该类的数据需要自己添加或者返回)
1.声明一个String类型的command(内容为linux命令)
2.声明一个Session对象,通过getSession方法获得返回值
Session session = SshUtil.getSession(类entity);
3.String类型获得结果
String result = SshUtil.getResult(session, command);
4.可将String类型进行转换