`
zb5594921
  • 浏览: 19132 次
社区版块
存档分类
最新评论

JAVA 调用linux shell命令

阅读更多

package com.test.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.cnunisoft.util.TextLogger;

public class JavaShellUtil {
	
	/**
	 * 调用方法为: 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",false);
	 * @param shellCommand
	 * @return
	 * @throws IOException
	 */
	public static int executeShell(String shellCommand,boolean waitFor) throws IOException {
		int success = 1;//默认是成功的 
		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("exec Shell:").append(shellCommand)
					.append(" \r\n");

			Process pid = null;
			//String[] cmd = { "/bin/sh", "-c", shellCommand };
			// 执行Shell命令
			pid = Runtime.getRuntime().exec(shellCommand);
			if (pid != null) {
				stringBuffer.append("pid:").append(pid.toString())
						.append("\r\n");
				if(waitFor){
					pid.waitFor();
				}
				bufferedReader = new BufferedReader(new InputStreamReader(
						pid.getInputStream()), 1024);
			} else {
				stringBuffer.append("no pid\r\n");
			}
			stringBuffer.append(dateFormat.format(new Date())).append(
					"Shell result:\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 Exception:\r\n").append(ioe.getMessage())
					.append("\r\n");
			success = 0;
		} finally {
			if(bufferedReader!=null){
				bufferedReader.close();
			}
			TextLogger.getLogger().warning(stringBuffer.toString());
		}
		return success;
	}
	
	/**
	 * 带返回值的shell调用
	 * 注意linux并不是所有的都有返回值的,要特殊处理ls是有的 ,但是ps -ef|grep就么有 
	 * @param shellCommand
	 * @return
	 * @throws IOException
	 */
	public static String executeShellWidthReturn(String shellCommand){
		//返回值
		StringBuffer stringBufferReturn = new StringBuffer();
		//记录日志
		StringBuffer stringBufferLog = new StringBuffer();
		// 格式化日期时间,记录日志时使用
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
		InputStreamReader ir = null;
		try {
			stringBufferLog.append(dateFormat.format(new Date()))
					.append("Will Exec Shell:").append(shellCommand)
					.append(" \r\n");

			Process process = null;
			//String[] cmd = { "/bin/sh", "-c", shellCommand };
			// 执行Shell命令
			process = Runtime.getRuntime().exec(shellCommand);
			// ir用于读取Shell的输出内容
			ir=new InputStreamReader(process.getInputStream()); 
			LineNumberReader input = new LineNumberReader (ir);
			if (process == null){
				stringBufferLog.append("Exec Error\r\n");
			}
			stringBufferLog.append(dateFormat.format(new Date())).append(
					"Exec Completed \r\nResult:\r\n");
			String line = null;
			// 读取Shell的输出内容,并添加到stringBuffer中
			 while ((line = input.readLine ()) != null) {
				stringBufferLog.append(line).append("\r\n");
				stringBufferReturn.append(line);
			}
		} catch (Exception ioe) {
			stringBufferLog.append("Exec Exception:\r\n").append(ioe.getMessage())
					.append("\r\n");
		} finally {
			if(ir!=null){
				try {
					ir.close();
				} catch (IOException e) {
				}
			}
			TextLogger.getLogger().warning(stringBufferLog.toString());
		}
		return stringBufferReturn.toString();
	}
	
	/**
	 * 调用方法为: 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",false);
	 * @param shellCommand
	 * @return
	 * @throws IOException
	 */
	public static int executeCommand(String shellCommand,boolean waitFor) throws IOException {
		int success = 1;//默认是成功的 
		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("exec 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("pid:").append(pid.toString())
						.append("\r\n");
				if(waitFor){
					pid.waitFor();
				}
				bufferedReader = new BufferedReader(new InputStreamReader(
						pid.getInputStream()), 1024);
			} else {
				stringBuffer.append("no pid\r\n");
			}
			stringBuffer.append(dateFormat.format(new Date())).append(
					"Shell result:\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 Exception:\r\n").append(ioe.getMessage())
					.append("\r\n");
			success = 0;
		} finally {
			if(bufferedReader!=null){
				bufferedReader.close();
			}
			TextLogger.getLogger().warning(stringBuffer.toString());
		}
		return success;
	}
}



分享到:
评论

相关推荐

    Java 调用 Linux shell 命令执行框架:sshxcute

    sshxcute 就是这样一个框架工具集,它基于 JSCH 构建,允许工程师利用Java 代码通过 SSH 连接远程批量执行 Linux/UNIX 系统上的命令或者脚本,同时加入了判断成功与否,取回输出等多种实用功能。sshxcute 不管是针对...

    Java调用linux shell脚本的方法

    本文将详细探讨如何在Java程序中调用Linux shell脚本,并解释相关的关键概念和步骤。 首先,调用shell脚本的基本过程分为以下几个步骤: 1. **设置脚本执行权限**:在Linux系统中,执行一个文件(如shell脚本)...

    java调用shell(包含有参数的调用)

    总之,Java调用Shell脚本是一个有效的方法来在Java程序中实现复杂的Linux环境下的操作,这种技术尤其适用于需要进行系统级操作和自动化任务的场景。掌握这一技术可以帮助开发者更好地实现跨平台的功能,尤其是在开发...

    linux shell脚本启动java类

    详细的linux shell脚本启动java代码类。

    java调用linux系统命令

    java调用linux系统命令的封装工具类。

    java连接linux,执行shell命令的工具类 sshxcute.jar

    在Java开发中,有时我们需要远程连接到Linux服务器执行shell命令,比如进行系统管理、自动化运维或者数据处理等任务。在这种情况下,使用SSH(Secure Shell)协议是常见的解决方案,因为它提供了安全的网络通信。...

    java调用shell脚本执行sqlldr与存储过程

    因为我在linux环境下执行shell脚本时sqlldr命令和sqlplus命令是正常执行的,没有任何问题,但是在java代码中调用脚本时却报错,所有排除了其他原因,只可能是环境变量的问题, 于是我把oracle的所有环境变量直接复制...

    java执行linux命令,java调用linux脚本文件,java启动停止发布tomcat,servlet ajax文件上传

    java 执行linux命令源码,java调用shell脚本源码,java web发布war到tomcat,servlet文件上传,ajax文件上传。 java web 上传war包、停止、启动、发布tomcat。 命令修改成自己的目录即可使用。

    JAVA操作linux服务器,本文用于启动shell脚本并返回数据,简单易懂,可随时修改

    连接成功后,我们可以通过`Session.execCommand()`方法执行shell命令或者脚本。例如,我们可以将要运行的shell脚本路径作为命令传递,服务器会执行该脚本并返回输出。 3. **接收数据**: 执行命令后,我们需要...

    java 远程调用Shell脚本客户端包

    Java 远程调用Shell脚本客户端包是一个实用的工具,专为开发者设计,使得在Java应用程序中执行远程Shell命令变得简单而高效。这个包的主要功能是通过Java代码发起对远程服务器上的Shell脚本的调用,从而实现跨平台的...

    Java 调用 Linux 命令实战(含完整代码)1

    本文将详细介绍如何使用Java调用Linux命令,以满足特定场景的需求,如文中提到的通过Java接口重启keepalived服务。首先,我们将理解Java调用Linux命令的基本原理,然后通过具体的代码示例来展示实现这一功能的过程。...

    java调用shell脚本

    在`java程序中调用linux命令.txt`文件中,可能包含了如何在Java程序中直接调用Linux命令的示例代码。通常,我们可以使用`Runtime.getRuntime().exec()`或`ProcessBuilder`类来执行命令。例如: ```java Process ...

    java调用Shell脚本.doc

    ### Java调用Shell脚本详解 #### 一、前言 在实际开发过程中,经常会遇到需要结合Java程序与Shell脚本进行操作的情况。通过Java调用Shell脚本不仅可以实现复杂的功能,还可以提高程序的灵活性和扩展性。本文将详细...

    java调用shell命令实现实例

    基于sshConnect的linux服务器的shell命令调用,并获取命令返回结果的实例。亲测有效!

    Java调用Shell脚本代码

    在Java程序中调用Unix/Linux主机上的Shell命令,并返回相应执行结果。

    使用runtime实现linux命令行或shell脚本多次调用

    在标题提到的场景中,我们需要多次调用Linux命令或shell脚本。`Runtime.exec(String command)`方法用于执行单个命令,而如果需要执行包含多个命令的shell脚本,可以使用`Runtime.exec(String[] cmdArray)`,其中...

    linux下shell脚本实现数据的导出

    总结来说,这个场景涉及到了Linux下的shell脚本编写,主要是使用`exp`命令导出Oracle数据库中的数据,并通过Java程序来调用这个脚本。这在日常的运维工作中非常常见,通过这种方式可以实现自动化数据备份,提高工作...

    Java调用shell脚本

    首先,Java调用shell脚本主要通过`Runtime`类或`ProcessBuilder`类来实现。`Runtime.getRuntime().exec()`方法允许我们执行系统命令,而`ProcessBuilder`提供了更灵活的命令构建和环境变量设置功能。下面是一个基本...

    java调用shell向DataX传递参数,where条件,包含特殊字符

    总之,Java调用shell脚本向DataX传递参数,尤其是在where条件中包含特殊字符时,需要关注字符串转义、shell命令构建以及安全问题。同时,合理设计和使用配置文件能有效提高代码的灵活性和可维护性。

    java调用shell脚本完美封装

    在Java编程中,有时我们需要与操作系统进行交互,执行一些系统级别的任务,比如自动化运维、文件管理等,这时就可能需要用到调用Shell脚本。本文将详细介绍如何在Java中完美封装shell脚本的调用方法,并提供相关的...

Global site tag (gtag.js) - Google Analytics