使用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;
        }
    }
}

你可能感兴趣的:(Java,shell,java)