美文网首页
java (fx) 远程执行Shell命令小工具样例

java (fx) 远程执行Shell命令小工具样例

作者: 一介书生独醉江湖 | 来源:发表于2023-10-17 14:35 被阅读0次

一、pom.xml

        <dependency>
            <groupId>org.jvnet.hudson</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210-hudson-1</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

二、工具类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.commons.lang.StringUtils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class RemoteShellTool {
    private Connection conn;
    private String ipAddr;
    private String charset = Charset.defaultCharset().toString();
    private String userName;
    private String password;

    public RemoteShellTool(String ipAddr, String userName, String password,
                           String charset) {
        this.ipAddr = ipAddr;
        this.userName = userName;
        this.password = password;
        if (charset != null) {
            this.charset = charset;
        }
    }
    /**
     *
     * @Title: login
     * @Description: 用户名密码方式  远程登录linux服务器
     * @return: Boolean
     * @throws
     */
    public boolean login(){
        boolean flag = false;
        try {
            conn = new Connection(ipAddr);
            conn.connect(); // 连接
            flag = conn.authenticateWithPassword(userName, password); // 认证
            if (flag) {
                System.out.println("=========登陆xxx服务器的用户名和密码认证成功!");
            } else {
                System.out.println("=========登陆xxx服务器的用户名和密码认证失败!");;
                conn.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
    /**
     *
     * @Title: processStdout
     * @Description: 解析脚本执行的返回结果
     * @param in 输入流对象
     * @param charset 编码
     * @return String 以纯文本的格式返回
     * @throws
     */
    public String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
    /**
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @param cmds
     *      即将执行的命令
     * @return
     *      命令执行完后返回的结果值,如果命令执行失败,返回空字符串,不是null
     * @since V0.1
     */
    public String exec(String cmds) {
        String result = "";
        try {
            if (this.login()) {
                Session session = conn.openSession(); // 打开一个会话
                session.execCommand(cmds);
                result = this.processStdout(session.getStdout(), this.charset);
                if(StringUtils.isBlank(result)){// 如果为得到标准输出为空字符串,说明脚本执行出错了
                    result = processStdout(session.getStderr(),this.charset);
                    System.out.println("-----返回空字符串-----:"+result);
                }
                session.close();
                conn.close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return result;
    }


}

三、JAVAFX hello-view.fxml(番外)

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>

<?import javafx.scene.control.Button?>
<VBox alignment="CENTER" spacing="5.0" xmlns:fx="http://javafx.com/fxml"
      fx:controller="com.example.central.HelloController">
    <padding>
        <Insets bottom="5.0" left="5.0" right="5.0" top="5.0"/>
    </padding>

    <Label fx:id="welcomeText"/>
<!--    <Button text="Hello!" onAction="#onHelloButtonClick"/>-->

    <Label fx:id="turnOffInternal"/>
    <Button text="关闭内网" onAction="#onTurnOffInternalButtonClick"/>

    <Label fx:id="turnOffExternal"/>
    <Button text="关闭外网" onAction="#onTurnOffExternalButtonClick"/>

    <Label fx:id="startIntranet"/>
    <Button text="启动内网" onAction="#onStartIntranetButtonClick"/>

    <Label fx:id="startExternal"/>
    <Button text="启动外网" onAction="#onStartExternalButtonClick"/>

    <Label fx:id="restartInternal"/>
    <Button text="重启内网" onAction="#onRestartInternalButtonClick"/>

    <Label fx:id="restartExternal"/>
    <Button text="重启外网" onAction="#onRestartExternalButtonClick"/>
    
</VBox>

四、JAVAFX HelloController.java(番外)

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import com.example.central.util.RemoteShellTool;
import org.apache.commons.lang.StringUtils;


public class HelloController {
    @FXML
    private Label welcomeText;

    @FXML
    protected void onHelloButtonClick() {
        welcomeText.setText("Welcome to JavaFX Application!");
    }

    @FXML
    protected void onTurnOffInternalButtonClick() {
        welcomeText.setText("***关闭内网***");

        /**=============拼接脚本命令start==========================*/
        StringBuffer stringBuffer = new StringBuffer("sh /opt/tomcat_nsp/bin/shutdown.sh");
        String str = stringBuffer.toString();
        /**=============拼接脚本命令end==========================*/

        String result = exec(str);
        welcomeText.setText("关闭内网 : " + (StringUtils.isEmpty(result) ? "Tomcat stoped" : result));
    }
    @FXML
    protected void onTurnOffExternalButtonClick() {
        welcomeText.setText("***关闭外网***");

        /**=============拼接脚本命令start==========================*/
        StringBuffer stringBuffer = new StringBuffer("sh /opt/tomcat_nsp/bin/shutdown.sh");
        String str = stringBuffer.toString();
        /**=============拼接脚本命令end==========================*/

        String result = exec(str);
        welcomeText.setText("关闭外网 : " + (StringUtils.isEmpty(result) ? "Tomcat stoped" : result));
    }
    @FXML
    protected void onStartIntranetButtonClick() {
        welcomeText.setText("***启动内网***");

        /**=============拼接脚本命令start==========================*/
        StringBuffer stringBuffer = new StringBuffer("sh /opt/tomcat_nsp/bin/startup.sh");
        String str = stringBuffer.toString();
        /**=============拼接脚本命令end==========================*/

        String result = exec(str);
        welcomeText.setText("启动内网 : " + result);
    }
    @FXML
    protected void onStartExternalButtonClick() {
        welcomeText.setText("***启动外网***");

        /**=============拼接脚本命令start==========================*/
        StringBuffer stringBuffer = new StringBuffer("sh /opt/tomcat_nsp/bin/startup.sh");
        String str = stringBuffer.toString();
        /**=============拼接脚本命令end==========================*/

        String result = exec(str);
        welcomeText.setText("启动外网 : " + result);
    }
    @FXML
    protected void onRestartInternalButtonClick() {
        welcomeText.setText("***重启内网***");

        /**=============拼接脚本命令start==========================*/
        StringBuffer stringBuffer = new StringBuffer("sh /opt/tomcat_nsp/bin/shutdown.sh");
        String str = stringBuffer.toString();
        /**=============拼接脚本命令end==========================*/
        String result = exec(str);
        welcomeText.setText("重启内网 : " + result);

        /**=============拼接脚本命令start==========================*/
        stringBuffer = new StringBuffer("sh /opt/tomcat_nsp/bin/startup.sh");
        str = stringBuffer.toString();
        /**=============拼接脚本命令end==========================*/
        result = exec(str);
        welcomeText.setText("重启内网 : " + result);
    }


    @FXML
    protected void onRestartExternalButtonClick() {
        welcomeText.setText("***重启外网***");

        /**=============拼接脚本命令start==========================*/
        StringBuffer stringBuffer = new StringBuffer("sh /opt/tomcat_nsp/bin/shutdown.sh");
        String str = stringBuffer.toString();
        /**=============拼接脚本命令end==========================*/
        String result = exec(str);
        welcomeText.setText("重启外网 : " + result);

        /**=============拼接脚本命令start==========================*/
        stringBuffer = new StringBuffer("sh /opt/tomcat_nsp/bin/startup.sh");
        str = stringBuffer.toString();
        /**=============拼接脚本命令end==========================*/

        result = exec(str);
        welcomeText.setText("重启外网 : " + result);
    }

    private String exec(String commandStr){
        System.out.println("执行脚本命令 : " + commandStr);

        /**=============调用远程工具类start==========================*/
        RemoteShellTool tool = new RemoteShellTool("192.168.1.111", "root",
                "YOUR PASSWORD", "utf-8");//调用工具类,参数1为远程电脑的ip,参数2位用户名,参数3位密码,参数4位编码方式
        String result = tool.exec(commandStr);//返回执行结果
        /**=============调用远程工具类end==========================*/

        if(result.contains("1")){//说明脚本执行成功,返回执行结果1
            System.out.println("-----脚本执行成功了,返回的结果值为-----:"+result);
        }else if(result.contains("0")){// 说明脚本执行失败,返回执行结果0
            System.out.println("-----脚本执行失败了,返回的结果值为-----:"+result);
        }
        System.out.println("------输出返回结果--------: "+result);
        return result;
    }
}

五、JAVAFX HelloApplication.java(番外)

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 300, 400);
        stage.setTitle("服务器重启工具!");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}
# 运行如下:
image.png
参考:
https://blog.51cto.com/u_16099168/6357113

相关文章

网友评论

      本文标题:java (fx) 远程执行Shell命令小工具样例

      本文链接:https://www.haomeiwen.com/subject/vdxqidtx.html