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

本文介绍在Linux环境下如何运行和调用Shell脚本文件,并通过Java程序实现本地和远程调用,包括参数传递和错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

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

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

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

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();

		}
	}

zpy.sh 文件

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

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包依赖

<!--调用远程服务器上的shell-->
<dependency>
    <groupId>org.jvnet.hudson</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210-hudson-1</version>
</dependency>
 /**
     * 执行远程服务器上的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);//本机调用

    }

}

问我shell脚本怎么写的,emmmm这个我也不太懂,是我们数据库dba写的,贴一份你们自己看看叭

#!/bin/bash

source /etc/profile
source ~/.bash_profile

###########################################################################
# SCRIPT: import_checkline.sh
# AUTHOR: YEKS
# DATE  : 2019-4-06
# REV   : 1.0.A
#               (Valid are A, B, D, T and P)
#         (For Alpha, Beta, Dev, Test and Production)
#
# PLATFORM: Linux
# 
# PURPOSE:
#      --shp
#      --dbf
#      --location-info
#      --check-line-geo
#      --project-id
#      --check-line-station
#      --abs-distance
#      --buffer-distance
#      --max-length
#      --max-related-distance
#      --check-line-info-name
#      --import-info-name
#      --import-task-id
#      --check-line-id
#
# REV LIST:
#         
#
#
#
###########################################################################

###########################################################################
#  DEFINE FILES AND VARIABLES HERE
###########################################################################

# The Program Path
WORK_DIR=/home/sms/scripts

# The Log Path
LOG_DIR=$WORK_DIR/log

# Lock Path
LCK_DIR=$WORK_DIR/lck

# The Program Name
progname=dispatch

# Parameter Virables
while getopts ":-:" opt 
do
    case $opt in
    -)
        case "${OPTARG}" in 
            shp)
            shp="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            shp=*)
            shp=${OPTARG#*=}
            ;;
            dbf)
            dbf="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            dbf=*)
            dbf=${OPTARG#*=}
            ;;
            location-info)
            locationinfo="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            location-info=*)
            locationinfo=${OPTARG#*=}
            ;;
            check-line-geo)
            checklinegeo="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            check-line-geo=*)
            checklinegeo=${OPTARG#*=}
            ;;
            project-id)
            projectId="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            project-id=*)
            projectId=${OPTARG#*=}
            ;;
            check-line-station)
            checklinestation="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            check-line-station=*)
            checklinestation=${OPTARG#*=}
            ;;
            abs-distance)
            absdistance="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            abs-distance=*)
            absdistance=${OPTARG#*=}
            ;;
            buffer-distance)
            bufferdistance="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            buffer-distance=*)
            bufferdistance=${OPTARG#*=}
            ;;                        
            max-length)
            maxlength="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            max-length=*)
            maxlength=${OPTARG#*=}
            ;;
            max-related-distance)
            maxrelateddistance="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            max-related-distance=*)
            maxrelateddistance=${OPTARG#*=}
            ;;
            check-line-info-name)
            checklineinfoname="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            check-line-info-name=*)
            checklineinfoname=${OPTARG#*=}
            ;;
            check-line-id)
            checklineid="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            check-line-id=*)
            checklineid=${OPTARG#*=}
            ;;
            import-info-name)
            importinfoname="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            import-info-name=*)
            importinfoname=${OPTARG#*=}
            ;;
            import-task-id)
            taskid="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            import-task-id=*)
            taskid=${OPTARG#*=}
            ;;
            db-info)
            dbinfo="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
            ;;
            db-info=*)
            dbinfo=${OPTARG#*=}
            ;;
            *)
            ;;
        esac;;
    ?)
    echo "usage: $0 [--shp --dbf --location-info --check-line-geo --check-line-id --project-id --check-line-station --abs-distance --buffer-distance --max-length --max-related-distance --check-line-info-name --import-info-name --import-task-id --db-info ]"
    exit 1
    ;;
    esac
done

if [[ -z $taskid && -z $inputfiledir && -z $outputfiledir ]]; then
    echo "usage: $0 [--shp --dbf --location-info --check-line-geo --check-line-id --project-id --check-line-station --abs-distance --buffer-distance --max-length --max-related-distance --check-line-info-name --import-info-name --import-task-id --db-info ]"
    exit 1
fi


# The Database Path
export NLS_LANG="American_America.ZHS16GBK"
export LANG="zh_CN.GBK"
export ORACLE_HOME=/u01/app/oracle/product/12.1.0.2/client_1

ORA_SID=dev
ORA_USER=jtgl
ORA_PASS=czty_jtgl


###########################################################################
#  DEFINE FUNCTION HERE
###########################################################################

if [[ ! -d $LOG_DIR ]]; then
    mkdir -p $LOG_DIR
fi

if [[ ! -d $LCK_DIR ]]; then
    mkdir -p $LCK_DIR
fi

prog(){

    sid=$$
    dt=`date +"%Y%m%d%H%M%S"`
    flag=`ls -la $LOG_DIR | grep "${taskid}_checkline_" | wc -l`
    if [[ "$flag" == "0" ]]; then 
        >> $LOG_DIR/${taskid}_checkline_${dt}.log
        nohup  $WORK_DIR/checkline/checkline --shp=$shp --dbf=$dbf --location-info=$locationinfo --check-line-geo=$checklinegeo --project-id=$projectId \
            --check-line-station=$checklinestation --abs-distance=$absdistance --buffer-distance=$bufferdistance --max-length=$maxlength \
            --max-related-distance=$maxrelateddistance --check-line-info-name=$checklineinfoname --import-info-name=$importinfoname \
            --import-task-id=$taskid --check-line-id=$checklineid --db-info=$dbinfo >> $LOG_DIR/${taskid}_checkline_${dt}.log 
    fi

    exit 0

}

###########################################################################
#  BEGINNING OF MAIN
########################################################################### 

prog

 

评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值