All things are difficult before they are easy. 没有软件的裸机是一具僵尸,没有硬件的软件是一个幽灵。2012,专注于Linux和C语言,关注自动化、性能测试,关注开源社区和开源测试工具、方法,尝试测试团队管理!

Ruby/C/Java调用Shell脚本

上一篇 / 下一篇  2010-11-27 00:05:52 / 个人分类:Java

Linux环境下工作的话,Shell脚本是经常用到,在很多其他程序中都有可能调用到。被人问到,怎样在Ruby程序中调用Shell脚本;经过总结整理,我分别说明一下如何在Ruby、C、Java代码中怎样调用shell脚本吧。

Ruby中调用Shell有很多种方法;下面代码简单说明一下吧。
// 第一种 用反引号将shell命令引起来,如果是shell脚本可写上绝对路径(总之就是可以直接运行的)
ipinfo=`ifconfig`
puts ipinfo

// 第二种 用system函数来实现
system 'echo "hello $HOSTNAME"'

// 第三种 用IO类的popen方法
IO.popen("date") { |f| puts f.gets }

// 第四种 用Ruby标准库open3中的方法
require "open3"
stdin, stdout, stderr = Open3.popen3('date')
stdin.puts('')
stdout.gets
stderr.gets
其实还有其他一些方式,这里有篇博客写了Ruby调用shell的六种方法:
http://blackanger.blog.51cto.com/140924/43730

C程序中调用shell脚本,一般通过system函数来执行shell脚本。参考代码如下:
#include   <stdlib.h>
int main(int argc, char* argv[])
{
    system("echo 'hello world'");
    system("/bin/ls /home");
}
更多详细内容,可查一下system函数的用法。

Java中调用Shell脚本,一般通过运行时类Runtime的方法来实现(Runtime.getRuntime().exec),参考代码如下:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class CallShell {
    public static void main(String[] args) {
        try {
            // 被注释掉的这个仅仅是执行了test.sh脚本,但没有获取它的输出
            // Runtime.getRuntime().exec("/home/master/workspace/shell/test.sh");
            Process process = Runtime.getRuntime().exec(
                    "/home/master/workspace/shell/test.sh");
            InputStreamReader ir = new InputStreamReader(process
                    .getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            while ((line = input.readLine()) != null)
                System.out.println(line);
            input.close();
            ir.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

另外,再附带贴一个,Java调用Shell并打印标准输出、标准错误的Java类,代码如下,供参考:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @className ShellCmdLog.java
 * @author 笑遍世界
 * @description Java程序调用一个系统的shell脚本,并且将标准输出和标准错误打印出来
 * @date 2010-11-26
*/
public class ShellCmdLog extends Thread {
    private boolean bLog2Error; // 是否打印错误Error标志
    private InputStream ins; // 待转换文件输入流

    /**
     * @param args
     */
    public static void main(String[] args) {
        // java调用shell脚本
        String path = "/home/master/workspace/shell/test.sh";// 脚本位于服务器中的路径
        String statement[] = { "/bin/sh", path };
        try {
            Process process = Runtime.getRuntime().exec(statement);
            InputStream in = process.getInputStream(); // 获取输入流
            InputStream err = process.getErrorStream();// 获取错误流

            ShellCmdLog sgStdout = new ShellCmdLog(in, false);
            ShellCmdLog sgStderr = new ShellCmdLog(err, true);

            sgStdout.start();
            sgStderr.start();

            // final int result = process.waitFor();

            // 为流读出捕获流设定的时间间隔。
            Thread.sleep(100);

            if (process != null) {
                process.destroy();
            }

            // 集合读取线程
            sgStdout.join();
            sgStderr.join();

        } catch (Exception e) {
            e.toString();
        }
    }

    /**
     * 设置是否打印错误Error,设置待转换文件的输入流
     *
     * @param is
     *            待转换文件输入流
     * @param flag
     *            是否打印错误Error标志
     */
    
    public ShellCmdLog(InputStream is, boolean flag) {
        super("ShellCmdStream" + (flag ? "-error" : "-out"));
        bLog2Error = flag;
        ins = is;
    }

    /**
     * 执行转换线程
     */
    public void run() {
        if (ins != null) {
            InputStreamReader isr = new InputStreamReader(ins);
            BufferedReader br = new BufferedReader(isr);
            try {
                String line = null;
                while ((line = br.readLine()) != null) {
                    if (bLog2Error) {
                        System.out.println("Shell_Err>" + line);
                    } else {
                        System.out.println("Shell_Out>" + line);
                    }
                } // end of while(true)
            } catch (IOException ioe) {
                System.out.println("ShellCmdLog error:" + ioe);
            } finally {
                try {
                    if (isr != null) {
                        isr.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

参考资料:
http://blackanger.blog.51cto.com/140924/43730
http://blog.csdn.net/hanqunfeng/archive/2009/07/10/4337529.aspx
http://www.cxyclub.cn/n/1232/
http://hi.baidu.com/migney/blog/item/1e6cd01f764d87f2e0fe0b8a.html
http://renyongjie668.blog.163.com/blog/static/16005312010102703721846/


TAG: java JAVA Java Ruby ruby shell Shell 调用shell脚本

 

评分:0

我来说两句

smile665

smile665

Stay hungry, stay foolish. 得意之时谨记,一半命运还掌握在上帝手里;失意之时须知,一半命运还掌握在自己手里。

日历

« 2024-04-12  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 954261
  • 日志数: 220
  • 建立时间: 2008-11-06
  • 更新时间: 2012-10-06

RSS订阅

Open Toolbar