zoukankan      html  css  js  c++  java
  • Java执行Dos-Shell脚本


    相关参考内容原文地址:

    bldong:Java 执行Shell脚本指令


    1、介绍

    在Linux中运行Java程序时,需要调用一些Shell命令和脚本。而Runtime.getRuntime().exec()方法给我们提供了这个功能,而且Runtime.getRuntime()给我们提供了以下几种exec()方法:

    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)
    在有指定环境和工作目录的独立进程中执行指定的字符串命令。
    

    如果参数中如果没有envp参数或设为null,表示调用命令将在当前程序执行的环境中执行;如果没有dir参数或设为null,表示调用命令将在当前程序执行的目录中执行,因此调用到其他目录中的文件和脚本最好使用绝对路径。

    各个参数的含义:

    1. cmdarray: 包含所调用命令及其参数的数组。
    2. command: 一条指定的系统命令。
    3. envp: 字符串数组,其中每个元素的环境变量的设置格式为name=value;如果子进程应该继承当前进程的环境,则该参数为 null。
    4. dir: 子进程的工作目录;如果子进程应该继承当前进程的工作目录,则该参数为 null。

    通过调用Process类的以下方法,得知调用操作是否正确执行:

    abstract  int waitFor()
    导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。
    

    2、调用shell脚本

    2.1 获取键盘输入

    BufferedReader reader = null;
            try{
                reader = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("请输入IP:");
                String ip = reader.readLine();
    

    上述指令基本很常见:

    1. 创建读入器:BufferReader
    2. 将数据流载入BufferReader,即InputStreamReader
    3. 将系统输入载入InputStreamReader中
    4. 然后利用reader获取数据。

    2.2 构建指令

    shell运行脚本指令为 sh **.sh args。

    #!/bin/sh
    #根据进程名杀死进程
    echo "This is a $call"
    if [ $# -lt 2 ]
    then   echo "缺少参数:procedure_name和ip"   exit 1
    fi
    echo "Kill the $1 process"
    PROCESS=`ps -ef|grep $1|grep $2|grep -v grep|grep -v PPID|awk '{ print $2}'`
    for i in $PROCESS
    do   echo "Kill the $1 process [ $i ]"
    done
    

    注意事项:

    1. shell脚本必须有执行权限,比如部署后chmod -R 777 /webapps
    2. shell文件,必须是UNIX格式,ANSI编码格式,否则容易出问题(可以用notepad++,编辑->文档格式转换,格式->转为ANSI格式(UNIX格式)

    2.3 Java代码

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class TestBash {
        public static void main(String [] args){
            BufferedReader reader = null;
            try{
                reader = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("请输入IP:");
                String ip = reader.readLine();
                String bashCommand = "sh "+ "/usr/local/java/jdk1.8.0_121/lib/stopffmpeg.sh" + " ffmpeg " + ip;
    //            String bashCommand = "chmod 777 " + "/usr/local/java/jdk1.8.0_121/lib/stopffmpeg.sh" ;
    //            String bashCommand = "kill -9" + ip;
                System.out.println(bashCommand);
                Runtime runtime = Runtime.getRuntime();
                Process pro = runtime.exec(bashCommand);
                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("
    ");
                }
    
                String result = strbr.toString();
                System.out.println(result);
    
            }
            catch (IOException ec)
            {
                ec.printStackTrace();
            }
            catch (InterruptedException ex){
                ex.printStackTrace();
    
            }
        }
    }
    

    3、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("
    ");
    			}
    			String result = strbr.toString();
    			System.out.println(result);
    		}
    		catch (IOException ec)
    		{
    			ec.printStackTrace();
    		}
    		catch (InterruptedException ex){
    			ex.printStackTrace();
    		}
    	}
    

    4、Java调用远程的Shell脚本

    <!--调用远程服务器上的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"")//带有特殊符号的参数需要加上双引号
        }
    
  • 相关阅读:
    POJ 1003 解题报告
    POJ 1004 解题报告
    POJ-1002 解题报告
    vi--文本编辑常用快捷键之光标移动
    常用图表工具
    September 05th 2017 Week 36th Tuesday
    September 04th 2017 Week 36th Monday
    September 03rd 2017 Week 36th Sunday
    September 02nd 2017 Week 35th Saturday
    September 01st 2017 Week 35th Friday
  • 原文地址:https://www.cnblogs.com/aixing/p/13327137.html
Copyright © 2011-2022 走看看