java调用shell文件、远程调用shell文件并且传入参数、.sh文件执行的几种方法

linux 运行*.sh文件的方法:

在Linux系统下运行.sh文件有两种方法,比如我在root/zpy目录下有个zpy.sh文件

第一种(这种办法需要用chmod使得文件具备执行条件(x): chmod u+x zpy.sh):

1、在任何路径下,输入该文件的绝对路径/root/zpy/zpy.sh就可执行该文件(当然要在权限允许情况下)

java调用shell文件、远程调用shell文件并且传入参数、.sh文件执行的几种方法_第1张图片

2、cd到zpy.sh文件的目录下,然后执行./zpy.sh

java调用shell文件、远程调用shell文件并且传入参数、.sh文件执行的几种方法_第2张图片

第二种(这种办法不需要文件具备可执行的权限也可运行):

1、在该文件路径下sh加上文件名字即可,sh zpy.sh
2、在任意路径下,sh 加上文件路径及文件名称:sh /zpy/zpy.sh

java调用shell文件并且传入参数:

public static  void invokeShell(){
//方法1 执行字符串命令(各个参数1234之间需要有空格)
String path="sh /root/zpy/zpy.sh 1 2 3 4";
//方法2 在单独的进程中执行指定命令和变量。 
//第一个变量是sh命令,第二个变量是需要执行的脚本路径,从第三个变量开始是我们要传到脚本里的参数。
String[] path=new String[]{"sh","/root/zpy/zpy.sh","1","2","3","4"}; 
		try{
			Runtime runtime = Runtime.getRuntime();
			Process pro = runtime.exec(path);
			int status = pro.waitFor();
			if (status != 0)
			{
				System.out.println("Failed to call shell's command");
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			StringBuffer strbr = new StringBuffer();
			String line;
			while ((line = br.readLine())!= null)
			{
				strbr.append(line).append("\n");
			}

			String result = strbr.toString();
			System.out.println(result);

		}
		catch (IOException ec)
		{
			ec.printStackTrace();
		}
		catch (InterruptedException ex){
			ex.printStackTrace();

		}
	}

java调用shell文件、远程调用shell文件并且传入参数、.sh文件执行的几种方法_第3张图片

zpy.sh 文件

java调用shell文件、远程调用shell文件并且传入参数、.sh文件执行的几种方法_第4张图片

根据需要调用不同的方法:

Process exec(String command) 
          在单独的进程中执行指定的字符串命令。 
 Process exec(String[] cmdarray) 
          在单独的进程中执行指定命令和变量。 
 Process exec(String[] cmdarray, String[] envp) 
          在指定环境的独立进程中执行指定命令和变量。 
 Process exec(String[] cmdarray, String[] envp, File dir) 
          在指定环境和工作目录的独立进程中执行指定的命令和变量。 
 Process exec(String command, String[] envp) 
          在指定环境的单独进程中执行指定的字符串命令。 
 Process exec(String command, String[] envp, File dir) 
          在有指定环境和工作目录的独立进程中执行指定的字符串命令。 

 

 

调用远程的shell脚本:pom 添加jar包依赖



    org.jvnet.hudson
    ganymed-ssh2
    build210-hudson-1
 /**
     * 执行远程服务器上的shell脚本
     * @param ip 服务器IP地址
     * @param port  端口号
     * @param name  登录用户名
     * @param pwd  密码
     * @param cmds shell命令
     */
    public static void RemoteInvokeShell(String ip,int port,String  name,String pwd,String cmds) {
       
        Connection conn=null;
        try {
            conn = new Connection(ip,port);
            conn.connect();
            if (conn.authenticateWithPassword(name, pwd)) {
                // Open a new {@link Session} on this connection
                Session session = conn.openSession();
                // Execute a command on the remote machine.
                session.execCommand(cmds);

                BufferedReader br = new BufferedReader(new InputStreamReader(session.getStdout()));
                BufferedReader brErr = new BufferedReader(new InputStreamReader(session.getStderr()));

                String line;
                while ((line = br.readLine()) != null) {
                    logger.info("br={}", line);
                }
                while ((line = brErr.readLine()) != null) {
                    logger.info("brErr={}", line);
                }
                if (null != br) {
                    br.close();
                }
                if(null != brErr){
                    brErr.close();
                }
                session.waitForCondition(ChannelCondition.EXIT_STATUS, 0);
                int ret = session.getExitStatus();
                logger.info("getExitStatus:"+ ret);
            } else {
                logger.info("登录远程机器失败" + ip);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }


 public static void main(String[] args){
        RemoteInvokeShell("192.168.11.xx",22,"xx","xx","sh /root/zpy/zpy.sh  \"jj|aa|bb\"")//带有特殊符号的参数需要加上双引号
    }

 

 

我程序中使用的:

package com.witsky.util;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by Administrator on 2019/4/22.
 */
public class InvokeShell {
    private static final Logger logger = LoggerFactory.getLogger(InvokeShell.class);

    /**
     * 调用shell脚本
     * @param path
     */

    public static void invokeShell(String [] path) {
        logger.info("invoke shell:{}", JSON.toJSONString(path));
        try {
            Runtime runtime = Runtime.getRuntime();
            Process pro = runtime.exec(path);
//            int status = pro.waitFor();
//            if (status != 0) {
//                logger.info("Failed to call shell's command ");
//            }
            BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            BufferedReader brErr = new BufferedReader(new InputStreamReader(pro.getErrorStream()));

            String line;
            while ((line = br.readLine()) != null) {
                logger.info("br={}", line);
            }
            while ((line = brErr.readLine()) != null) {
                logger.info("brErr={}", line);
            }
            if (null != br) {
                br.close();
            }
            if(null != brErr){
                brErr.close();
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
    }


    /**
     * 执行远程服务器上的shell脚本
     * @param ip 服务器IP地址
     * @param port  端口号
     * @param name  登录用户名
     * @param pwd  密码
     * @param cmds shell命令
     */
    public static void RemoteInvokeShell(String ip,int port,String  name,String pwd,String[] cmds) {
        logger.info("ip:"+ip+" port:"+port+" name:"+name+" password:"+pwd);
        StringBuffer cmd=new StringBuffer();
        for(String s:cmds){
            if(s.contains("|")||s.contains(" ")){ //如果包含特殊符号
                s="\""+s+"\"";
            }
            cmd.append(s).append(" ");
        }
        String cmdd= cmd.toString();
        //cmdd=cmdd.substring(0,cmdd.length()-1);
        logger.info("invoke shell:{}",cmdd);
        Connection conn=null;
        try {
            conn = new Connection(ip,port);
            conn.connect();
            if (conn.authenticateWithPassword(name, pwd)) {
                // Open a new {@link Session} on this connection
                Session session = conn.openSession();
                // Execute a command on the remote machine.
                session.execCommand(cmdd);

                BufferedReader br = new BufferedReader(new InputStreamReader(session.getStdout()));
                BufferedReader brErr = new BufferedReader(new InputStreamReader(session.getStderr()));

                String line;
                while ((line = br.readLine()) != null) {
                    logger.info("br={}", line);
                }
                while ((line = brErr.readLine()) != null) {
                    logger.info("brErr={}", line);
                }
                if (null != br) {
                    br.close();
                }
                if(null != brErr){
                    brErr.close();
                }
                session.waitForCondition(ChannelCondition.EXIT_STATUS, 0);
                int ret = session.getExitStatus();
                logger.info("getExitStatus:"+ ret);
            } else {
                logger.info("登录远程机器失败" + ip);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }

    /**
     * 上传文件到远程服务器
     */
    public static void remoteUploadFile(String ip,int port,String  name,String pwd,String filePath,String fileName,File file) {
        logger.info("remoteUploadFile.... ");
        Connection connection = new Connection(ip,port);
        try {
            connection.connect();
            boolean isAuthenticated = connection.authenticateWithPassword(name,pwd);
            if(!isAuthenticated){
                logger.info("登录远程机器失败" + ip);
                return ;
            }
            SCPClient scpClient = new SCPClient(connection);
            scpClient.put(filePath+fileName, filePath);
            if(null!=connection){
                connection.close();
            }
            logger.info("upload ok");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        //调用脚本
        String path[]={"sh","/root/zpy/import_checkline.sh",//shell脚本的存放路径
                "--shp","aaa|bbb|ccc",//"--shp"代表的是shell脚本里面的参数名  aaa|bbb|ccc 代表参数值
                "--dbf","dddd",
                "--location-info","",
                "--check-line-geo","T_CHECKLINE_SUB_INFO",
                "--project-id","",
                "--check-line-station","T_CHECKLINE_LACCI",
                "--check-line-info-name","T_CHECKLINE_INFO",
                "--import-info-name","T_IMPORT_TASK",
                "--abs-distance","",
                "--buffer-distance","",
                "--max-length","",
                "--max-related-distance","",
                "--import-task-id","",
                "--check-line-id","",
                "--db-info",""
        };

        RemoteInvokeShell("ip",123,"name","ppwd",path);//远程调用
        invokeShell(path);//本机调用

    }

}

 

你可能感兴趣的:(java,springboot,java调用shell,java远程调用shell脚本)