java调用shell

近日项目中有这样一个需求:系统中的外币资金调度完成以后,要将调度信息生成一个Txt文件,然后将这个Txt文件发送到另外一个系统(Kondor)中。生成文件自然使用OutputStreamWirter了,发送文件有两种方式,一种是用写个一个类似于FTP功能的程序,另外一种就是使用Java来调用Shell,在Shell中完成文件的发送操作。我们选择后一种,即当完成外币资金的调度工作后,用Java的OutputStreamWriter来生成一个Txt文件,然后用Java来调用Shell脚本,在Shell脚本中完成FTP文件到Kondor系统的工作。
以下为Java程序JavaShellUtil.java:

Java代码 复制代码 收藏代码
  1. importjava.io.BufferedReader;
  2. importjava.io.File;
  3. importjava.io.FileOutputStream;
  4. importjava.io.IOException;
  5. importjava.io.InputStreamReader;
  6. importjava.io.OutputStream;
  7. importjava.io.OutputStreamWriter;
  8. importjava.text.DateFormat;
  9. importjava.text.SimpleDateFormat;
  10. importjava.util.Date;
  11. publicclassJavaShellUtil{
  12. //基本路径
  13. privatestaticfinalStringbasePath="/tmp/";
  14. //记录Shell执行状况的日志文件的位置(绝对路径)
  15. privatestaticfinalStringexecuteShellLogFile=basePath+"executeShell.log";
  16. //发送文件到Kondor系统的Shell的文件名(绝对路径)
  17. privatestaticfinalStringsendKondorShellName=basePath+"sendKondorFile.sh";
  18. publicintexecuteShell(StringshellCommand)throwsIOException{
  19. intsuccess=0;
  20. StringBufferstringBuffer=newStringBuffer();
  21. BufferedReaderbufferedReader=null;
  22. //格式化日期时间,记录日志时使用
  23. DateFormatdateFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:SS");
  24. try{
  25. stringBuffer.append(dateFormat.format(newDate())).append("准备执行Shell命令").append(shellCommand).append("\r\n");
  26. Processpid=null;
  27. String[]cmd={"/bin/sh","-c",shellCommand};
  28. //执行Shell命令
  29. pid=Runtime.getRuntime().exec(cmd);
  30. if(pid!=null){
  31. stringBuffer.append("进程号:").append(pid.toString()).append("\r\n");
  32. //bufferedReader用于读取Shell的输出内容bufferedReader=newBufferedReader(newInputStreamReader(pid.getInputStream()),1024);
  33. pid.waitFor();
  34. }else{
  35. stringBuffer.append("没有pid\r\n");
  36. }
  37. stringBuffer.append(dateFormat.format(newDate())).append("Shell命令执行完毕\r\n执行结果为:\r\n");
  38. Stringline=null;
  39. //读取Shell的输出内容,并添加到stringBuffer中
  40. while(bufferedReader!=null&
  41. &
  42. (line=bufferedReader.readLine())!=null){
  43. stringBuffer.append(line).append("\r\n");
  44. }
  45. }catch(Exceptionioe){
  46. stringBuffer.append("执行Shell命令时发生异常:\r\n").append(ioe.getMessage()).append("\r\n");
  47. }finally{
  48. if(bufferedReader!=null){
  49. OutputStreamWriteroutputStreamWriter=null;
  50. try{
  51. bufferedReader.close();
  52. //将Shell的执行情况输出到日志文件中
  53. OutputStreamoutputStream=newFileOutputStream(executeShellLogFile);
  54. outputStreamWriter=newOutputStreamWriter(outputStream,"UTF-8");
  55. outputStreamWriter.write(stringBuffer.toString());
  56. }catch(Exceptione){
  57. e.printStackTrace();
  58. }finally{
  59. outputStreamWriter.close();
  60. }
  61. }
  62. success=1;
  63. }
  64. returnsuccess;
  65. }
  66. }

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaShellUtil {
//基本路径
private static final String basePath = "/tmp/";

//记录Shell执行状况的日志文件的位置(绝对路径)
private static final String executeShellLogFile = basePath + "executeShell.log";

//发送文件到Kondor系统的Shell的文件名(绝对路径)
private static final String sendKondorShellName = basePath + "sendKondorFile.sh";

public int executeShell(String shellCommand) throws IOException {
int success = 0;
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = null;
//格式化日期时间,记录日志时使用
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");

try {
stringBuffer.append(dateFormat.format(new Date())).append("准备执行Shell命令 ").append(shellCommand).append(" \r\n");

Process pid = null;
String[] cmd = {"/bin/sh", "-c", shellCommand};
//执行Shell命令
pid = Runtime.getRuntime().exec(cmd);
if (pid != null) {
stringBuffer.append("进程号:").append(pid.toString()).append("\r\n");
//bufferedReader用于读取Shell的输出内容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
pid.waitFor();
} else {
stringBuffer.append("没有pid\r\n");
}
stringBuffer.append(dateFormat.format(new Date())).append("Shell命令执行完毕\r\n执行结果为:\r\n");
String line = null;
//读取Shell的输出内容,并添加到stringBuffer中
while (bufferedReader != null &
&
(line = bufferedReader.readLine()) != null) {
stringBuffer.append(line).append("\r\n");
}
} catch (Exception ioe) {
stringBuffer.append("执行Shell命令时发生异常:\r\n").append(ioe.getMessage()).append("\r\n");
} finally {
if (bufferedReader != null) {
OutputStreamWriter outputStreamWriter = null;
try {
bufferedReader.close();
//将Shell的执行情况输出到日志文件中
OutputStream outputStream = new FileOutputStream(executeShellLogFile);
outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(stringBuffer.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStreamWriter.close();
}
}
success = 1;
}
return success;
}

}


以下是Shell脚本sendKondorFile.sh,该Shell脚本的作用是FTP文件到指定的位置:

Shell代码 复制代码 收藏代码
  1. #!/bin/sh
  2. #日志文件的位置
  3. logFile="/opt/fms2_kondor/sendKondorFile.log"
  4. #Kondor系统的IP地址,会将生成的文件发送到这个地址
  5. kondor_ip=192.168.1.200
  6. #FTP用户名
  7. ftp_username=kondor
  8. #FTP密码
  9. ftp_password=kondor
  10. #要发送的文件的绝对路径
  11. filePath=""
  12. #要发送的文件的文件名
  13. fileName=""
  14. #如果Shell命令带有参数,则将第一个参数赋给filePath,将第二个参数赋给fileName
  15. if[$#-ge"1"]
  16. then
  17. filePath=$1
  18. else
  19. echo"没有文件路径"
  20. echo"没有文件路径\n">
  21. >
  22. $logFile
  23. return
  24. fi
  25. if[$#-ge"2"]
  26. then
  27. fileName=$2
  28. else
  29. echo"没有文件名"
  30. echo"没有文件名\n">
  31. >
  32. $logFile
  33. return
  34. fi
  35. echo"要发送的文件是${filePath}/${fileName}"
  36. cd${filePath}
  37. ls$fileName
  38. if(test$?-eq0)
  39. then
  40. echo"准备发送文件:${filePath}/${fileName}"
  41. else
  42. echo"文件${filePath}/${fileName}不存在"
  43. echo"文件${filePath}/${fileName}不存在\n">
  44. >
  45. $logFile
  46. return
  47. fi
  48. ftp-n${kondor_ip}<
  49. <
  50. _end
  51. user${ftp_username}${ftp_password}
  52. asc
  53. prompt
  54. put$fileName
  55. bye
  56. _end
  57. echo"`date+%Y-%m-%d''%H:%M:%S`发送了文件${filePath}/${fileName}"
  58. echo"`date+%Y-%m-%d''%H:%M:%S`发送了文件${filePath}/${fileName}\n">
  59. >
  60. $logFile

#!/bin/sh

#日志文件的位置
logFile="/opt/fms2_kondor/sendKondorFile.log"

#Kondor系统的IP地址,会将生成的文件发送到这个地址
kondor_ip=192.168.1.200

#FTP用户名
ftp_username=kondor

#FTP密码
ftp_password=kondor

#要发送的文件的绝对路径
filePath=""

#要发送的文件的文件名
fileName=""

#如果Shell命令带有参数,则将第一个参数赋给filePath,将第二个参数赋给fileName
if [ $# -ge "1" ]
then
filePath=$1
else
echo "没有文件路径"
echo "没有文件路径\n" >
>
$logFile
return
fi

if [ $# -ge "2" ]
then
fileName=$2
else
echo "没有文件名"
echo "没有文件名\n" >
>
$logFile
return
fi

echo "要发送的文件是 ${filePath}/${fileName}"

cd ${filePath}
ls $fileName
if (test $? -eq 0)
then
echo "准备发送文件:${filePath}/${fileName}"
else
echo "文件 ${filePath}/${fileName} 不存在"
echo "文件 ${filePath}/${fileName} 不存在\n" >
>
$logFile
return
fi

ftp -n ${kondor_ip} <
<
_end
user ${ftp_username} ${ftp_password}
asc
prompt
put $fileName
bye
_end

echo "`date +%Y-%m-%d' '%H:%M:%S` 发送了文件 ${filePath}/${fileName}"
echo "`date +%Y-%m-%d' '%H:%M:%S` 发送了文件 ${filePath}/${fileName}\n" >
>
$logFile


调用方法为:

Java代码 复制代码 收藏代码
  1. JavaShellUtiljavaShellUtil=newJavaShellUtil();
  2. //参数为要执行的Shell命令,即通过调用Shell脚本sendKondorFile.sh将/temp目录下的tmp.pdf文件发送到192.168.1.200上
  3. intsuccess=javaShellUtil.executeShell("sh/tmp/sendKondorFile.sh/temptmp.pdf");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值