Metersphere+jar+beanshell+连接linux
Metersphere+jar+beanshell+连接linux
java编写连接linux代码
- 使用jsch连接linux,下载jsch包或者使用maven
<dependencies><dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.55</version></dependency></dependencies>
- 新建maven项目,或者选择项目右键把项目转化为maven项目
- 在src/main/java下,新建包,输入com.tools
- 在包下创建JschDemo类,代码如下:
package com.tools;import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;import java.io.InputStream;
public class JschDemo {public static void executeCommand(String host, String user, String password, String command) {try {JSch jsch = new JSch();Session session = jsch.getSession(user, host, 22);session.setPassword(password);session.setConfig("StrictHostKeyChecking", "no");session.connect();Channel channel = session.openChannel("exec");((ChannelExec) channel).setCommand(command);channel.setInputStream(null);((ChannelExec) channel).setErrStream(System.err);InputStream in = channel.getInputStream();channel.connect();byte[] tmp = new byte[1024];while (true) {while (in.available() > 0) {int i = in.read(tmp, 0, 1024);if (i < 0) break;System.out.print(new String(tmp, 0, i));}if (channel.isClosed()) {if (in.available() > 0) continue;System.out.println("exit-status: " + channel.getExitStatus());break;}try {Thread.sleep(1000);} catch (Exception ee) {}}channel.disconnect();session.disconnect();} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {JschDemo jschDemo = new JschDemo();jschDemo.executeCommand("xxxxx, "root", "xxxx","date -s \"2023-5-22 14:26\"");jschDemo.executeCommand("xxxxx", "root", "xxxx","ls");}
}
- 运行成功后,打jar包
- 选择项目右键,点open module settings
- 按下图选择
- 按下图
- 保留2个jar即可,点击确定
- 点击build菜单,选择build
- build完成后,到上面配置的路径下找到jar吧
上传jar包
访问metershpere,项目设置-文件管理
点击上传:
编写beanshell