需求:在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