Invoke linux shell in java

需求:在java里调用linux的shell脚本来实现自动执行某指令

 

解决方案:

java代码部分:

//取得服务器绝对路径
String path = request.getRealPath("/");

 //发送邮件命令
String cmd = "sh " +path + "shell/autosendmail.sh " + fromname + " " + fromdomain + " " + user_code  + " " + domain + " " + user_code + ".txt" + " " + mailSubject + " " + ipAddr + " " + sendport;
           
   try
   {
       System.out.println("start invoke send mail shell ...");

     //用getRunTime().exec(String)方法来调用linux shell
    Process p=Runtime.getRuntime().exec(cmd);
    
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); //正常输入流
    BufferedReader errorin = new BufferedReader(new InputStreamReader(p.getErrorStream()));    //错误输入流
    // read the ls output               
    String line;
    System.out.println("in.readLine() = " + in.readLine());
    System.out.println("errorin.readLine() = " + errorin.readLine());
    while ((line = in.readLine())!= null)
    {      

         //print 输入流
        System.out.println(line);        
    }                 
    // check for ls failure         
    try
    {              
        if (p.waitFor() != 0)
        {    

            //非正常结束
            System.err.println("exit value = " + p.exitValue());          
        }        
    }      
    catch (InterruptedException e)
    {          
        System.err.println(e); 

         throw new Exception("发送邮件进程非正常结束!");
    }
    
    System.out.println("autosend mail sucessed ...");
    
   }
   catch(Exception e)
   { 
    e.printStackTrace();
    throw new Exception("发送邮件失败!" + e.getMessage());
   }

 

Linux shell部分:

#!/bin/bash
export path = "/data/../../shell"
echo ./sendmail.dat $1 $2 $3 $4 $5 $6 $7 $8
cd $path
./sendmail.dat $1 $2 $3 $4 $5 $6 $7 $8

注:通过$1,$2,$3可以接受到来自于./autosendmail.sh username domain toaddr 中的usename,domain,toaddr

在shell中$1变量将被赋值为username;$2被赋值为domain;$3被赋值为toaddr

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值