基于linux学习的常用的shell命令调用

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

@Slf4j
public class Shell {

    public static String ec(String command) throws IOException {
        String returnString = "";
        Process pro = null;
        Runtime runTime = Runtime.getRuntime();
        if (runTime == null) {
            System.err.println("Create runtime false!");
        }
        BufferedReader input = null;
        PrintWriter output = null;
        try {
            log.info("shell start: " + command);
            pro = runTime.exec(command);
            log.info("shell end: " + command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                System.out.println(line);
                returnString = returnString + line + "\n";
                log.info("shell returnString: " + returnString);
            }
        } catch (IOException ex) {
            Logger.getLogger(Shell.class.getName()).log(Level.SEVERE, null, ex);
        }finally {
            input.close();
            log.info("shell ec: input.close");
            output.close();
            log.info("shell ec: output.close");
            pro.destroy();
            log.info("shell ec: pro.destroy");
        }
        return returnString;
    }

    @Test
    public void test() throws Exception {
        System.out.println(exec("ls -al"));
    }

}
//调用shell脚本,判断是否正常执行,如果正常结束,Process的waitFor()方法返回0
    public static void callShell(String shellString) {
        try {
            Process process = Runtime.getRuntime().exec(shellString);
            int exitValue = process.waitFor();
            if (0 != exitValue) {
                log.error("call shell failed. error code is :" + exitValue);
            }
        } catch (Throwable e) {
            log.error("call shell failed. " + e);
        }
    }
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaShellUtil {

    //基本路径
    //private static final String basePath = "/tmp/";
    private static final String basePath = System.getProperty("java.io.tmpdir");

    //记录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文件到指定的位置:

#!/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

调用方法为:

JavaShellUtil javaShellUtil = new JavaShellUtil();
//参数为要执行的Shell命令,即通过调用Shell脚本sendKondorFile.sh将/temp目录下的tmp.pdf文件发送到192.168.1.200上
int success = javaShellUtil.executeShell("sh /tmp/sendKondorFile.sh /temp tmp.pdf");

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值