1、编写自定义函数并编译
package com.fr.function;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.fr.script.AbstractFunction;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static com.fr.health.constants.ComponentHealthConstants.Status.TIME_OUT;
public class CustomSubmitJobCommon extends AbstractFunction {
@Override
public Object run(Object[] arg0) {
return executeRemoteCommandCommon();
}
private String executeRemoteCommandCommon() {
final String ipAddress = "127.0.0.1";
final String username = "root";
final String password = "123456";
final String command = "cd /usr/kettle_task/N_steelmaking/ceshi/cb_ceshiv1 && ./cb_ceshiv1.sh";
try{
Connection conn = new Connection(ipAddress);
conn.connect();
if (!conn.authenticateWithPassword(username, password)) {
System.err.printf("Failed to authenticate with username '%s' on server %s.", username, ipAddress);
return "用户名或密码错误";
}
try {
Session session = conn.openSession();
session.execCommand(command);
System.out.println(command);
InputStream stdOut = new StreamGobbler(session.getStdout());
InputStream stdErr = new StreamGobbler(session.getStderr());
printStream(stdOut, "STDOUT:");
printStream(stdErr, "STDERR:");
int exitStatus = session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
if (exitStatus == TIME_OUT) {
System.err.println("Command execution timed out.");
return "执行失败";
}
return "执行成功";
} finally {
conn.close();
}
} catch (IOException e) {
System.err.println("An error occurred during the SSH connection or command execution.");
e.printStackTrace();
return "连接失败";
}
}
private void printStream(InputStream in, String streamType) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(streamType + " " + line);
}
} catch (IOException e) {
System.err.println("Error reading from stream: " + e.getMessage());
}
}
public static void main(String[] args) {
CustomSubmitJobCommon job = new CustomSubmitJobCommon();
System.out.println(job.executeRemoteCommandCommon());
}
}
2、新增按钮,并添加点击事件,点击按钮后即可执行命令调用kettle作业。