使用Java代碼調用服務器shell腳本

shell腳本:

#!/bin/bash
num=$1
if [ $((num%2)) == 0 ];then
  echo "success";
else
  echo "error";
fi

連接shell腳本所在服務器:

package com.zhbr.dataImport.utils;

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.logging.Log;
import org.apache.commons.logging.LogFactory;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
/**
 * @ClassName ConnectShell
 * @Description 連接Shell腳本所在服務器
 * @Autor yanni
 * @Date 2020/3/30 16:52
 * @Version 1.0
 **/
public class ConnectShell {
    private Connection conn;
    private String ipAddr;
    private String userName;
    private String password;
    private String charset = Charset.defaultCharset().toString();
    private static final int TIME_OUT = 1000 * 5 * 60;
    public static Log log = LogFactory.getLog(ConnectShell.class);

    public ConnectShell(String ipAddr, String userName, String password, String charset) {
        this.ipAddr = ipAddr;
        this.userName = userName;
        this.password = password;
        if (charset != null) {
            this.charset = charset;
        }
    }

    public boolean login() throws IOException {
        conn = new Connection(ipAddr);
        conn.connect();
        return conn.authenticateWithPassword(userName, password); // 認證
    }

    /**
     *
     * @Title: excuteShellCommand
     * @Description: 執行shell腳本命令
     * @param shellpath
     * @return
     */
    public boolean excuteShellCommand(String shellpath) {
        InputStream in = null;
        boolean result = false;
        String str = "";
        try {
            if (this.login()) {
                Session session = conn.openSession();
                //session.execCommand("cd /root");
                session.execCommand(shellpath);
                in = new StreamGobbler(session.getStdout());
                // in = session.getStdout();
                str = this.processStdout(in, charset);
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                session.close();
                conn.close();
                if (str.contains("success")) {
                    result = true;
                }else{
                    result = false;
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return result;
    }

    public String excuteShellCommand2(String shellpath) throws Exception {
        InputStream in = null;
        String result = "";
        try {
            if (this.login()) {
                Process exec = Runtime.getRuntime().exec(shellpath);// ipconfig
                in = exec.getInputStream();
                result = this.processStdout(in, this.charset);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return result;
    }

    /**
     * 轉化結果
     *
     * @param in
     * @param charset
     * @return
     * @throws UnsupportedEncodingException
     */
    public String processStdout(InputStream in, String charset) throws UnsupportedEncodingException {
        String line = null;
        BufferedReader brs = new BufferedReader(new InputStreamReader(in, charset));
        StringBuffer sb = new StringBuffer();
        try {
            while ((line = brs.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            log.error("---轉化出現異常---");
        }
        return sb.toString();
    }

}

測試:

package com.zhbr.dataImport.test;

import com.zhbr.dataImport.utils.ConnectShell;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Properties;

/**
 * @ClassName TestJavaShell
 * @Description TODO
 * @Autor yanni
 * @Date 2020/3/30 16:53
 * @Version 1.0
 **/
public class TestJavaShell {
    /**
     * shell腳本所在服務器配置
     */
    //public static int SHELL_EXIT_OK = 0;
    public static Log log = LogFactory.getLog(TestJavaShell.class);
    public static String connIp = "192.168.72.141";
    public static String connUser = "root";
    public static String connPwd = "1a2b3c4d";

    public static void main(String[] args) throws Exception {
        boolean result = export();
        System.out.println(result);
    }

    public static boolean export() throws Exception {
        boolean result = false;
        // 如果當前系統是window系統需要遠程ssh連接系統
        if (isWinSystem()) {
            ConnectShell connectShell = new ConnectShell(connIp, connUser, connPwd, "utf-8");
            String url = "/root/gg.sh"+" "+2 ;
            result = connectShell.excuteShellCommand(url);
        }
        return result;
    }

    /**
     * 當前操作系統類型
     *
     * @return true 爲windos系統,false爲linux系統
     */
    public static boolean isWinSystem() {
        // 獲取當前操作系統類型
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os.startsWith("win") || os.startsWith("Win")) {
            return true;
        } else {
            return false;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章