工具類之----java調用shell腳本的工具ProcessTool類

在項目上,因爲是管理資源(就是管理所有的機器),那麼肯定會定義好許多的腳本(shell命令),通過java調用呢必須使用了一個工具類。如下

1、ProcessTool工具類

package com.simp.util.process;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.simp.env.ShellEnv;
import com.simp.property.Debug;

public class ProcessTool {
	private static String getNormalOutput(Process proc, boolean debug) {
		String rv = getOutput(proc.getInputStream(), debug);
		
		if (debug) {
			if (rv != null && rv.length() > 0) {
				Debug.info("exec normal output stream->" + rv);
			}
		}
		
		return rv;
	}

	private static String getErrorOutput(Process proc, boolean debug) {
		String rv = getOutput(proc.getErrorStream(), debug);
		
		if (debug) {
			if (rv != null && rv.length() > 0) {
				Debug.err("exec error stream->" + rv);
			}
		}
		
		return rv;
	}
		
	
	private static String getOutput(InputStream is, boolean debug) {
		byte[] buf = new byte[512];
		StringBuffer sb = new StringBuffer();
		
		try {
			int rv = 0;			
			while ((rv = is.read(buf)) > 0) {
				sb.append(new String(buf, 0, rv, "gbk"));			
			}
			
			return sb.toString();
		} catch (Exception e) {
		}

		return sb.toString();
	}
	
	public static boolean exec(String cmd) {
		return exec(cmd, 1000, false);
	}
	
	public static boolean exec(String cmd, boolean debug) {
		return exec(cmd, 1000, debug);
	}

	public static boolean exec(String cmd, long interval, boolean debug) {
		String cmd_arr[] = crt_cmd(cmd);
		
		return exec(cmd_arr, interval, debug);
	}
	
	public static boolean exec(String[] cmd, long interval, boolean debug) {
		Process proc = null;
		boolean rv = true;
		
		try {
			proc = Runtime.getRuntime().exec(cmd);

			Thread.sleep(interval);
			
			String err = getErrorOutput(proc, debug);
			if (err != null && err.length() > 0) {
				rv = false;
			} else {
				getNormalOutput(proc, debug);
			}

			proc.waitFor();
		} catch (Exception e) {
			Debug.err(e.getMessage());
			rv = false;
		} finally {
			destroy(proc);
		}

		return rv;
	}
	
	/**
	 * 執行整行命令,不分割成參數數組形式執行
	 * @param cmd
	 * @param interval
	 * @param debug
	 * @return
	 */
	public static boolean exec_c(String cmd, long interval, boolean debug) {
		boolean rv = true;

		if (debug) {
			Debug.info(cmd);
		}
		
		Process proc = null;
		
		try {
			proc = Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", cmd });

			Thread.sleep(interval);
			
			String err = getErrorOutput(proc, debug);
			if (err != null && err.length() > 0) {
				rv = false;
			} else {
				getNormalOutput(proc, debug);
			}

			proc.waitFor();
		} catch (Exception e) {
			Debug.err(e.getMessage());
			rv = false;
		} finally {
			destroy(proc);
		}

		return rv;
	}
	
	public static String exec_reply(String[] cmd, String char_set, long interval) {
		Process proc = null;
		String rv = "";
		try {
			if (cmd != null) {
				Debug.info(Arrays.toString(cmd));
			}
			
			proc = Runtime.getRuntime().exec(cmd);

			Thread.sleep(interval);
			
			rv = getNormalOutput(proc, char_set,  false);

			proc.waitFor();
		} catch (Exception e) {
			Debug.err(e.getMessage());
			return "error ["+e.getMessage()+"]eor";
		} finally {
			destroy(proc);
		}

		return rv;
	}
	
	private static String getNormalOutput(Process proc, String char_set, boolean debug) {
		String rv = getOutput(proc.getInputStream(), char_set, debug);
		
		if (debug) {
			if (rv != null && rv.length() > 0) {
				Debug.info("exec normal output stream->" + rv);
			}
		}
		
		return rv;
	}
	
	private static String getOutput(InputStream is, String char_set, boolean debug) {
		byte[] buf = new byte[512];
		StringBuffer sb = new StringBuffer();
		
		try {
			int rv = 0;			
			while ((rv = is.read(buf)) > 0) {
				sb.append(new String(buf, 0, rv, char_set));			
			}
			
			return sb.toString();
		} catch (Exception e) {
		}

		return sb.toString();
	}
	
	public static String exec_reply(String cmd, long interval) {
		Process proc = null;
		String rv = "";
		try {
			proc = Runtime.getRuntime().exec(
					new String[] { "/bin/bash", "-c", cmd });

			Thread.sleep(interval);
			
			rv = getNormalOutput(proc, true);

			proc.waitFor();
		} catch (Exception e) {
			Debug.err(e.getMessage());
		} finally {
			destroy(proc);
		}

		return rv;
	}
	
	public static String exec_reply(String[] cmd, long interval) {
		Process proc = null;
		String rv = "";
		try {
			if (cmd != null) {
				Debug.info(Arrays.toString(cmd));
			}
			
			proc = Runtime.getRuntime().exec(cmd);

			Thread.sleep(interval);
			
			rv = getNormalOutput(proc, false);

			proc.waitFor();
		} catch (Exception e) {
			Debug.err(e.getMessage());
			return "error ["+e.getMessage()+"]eor";
		} finally {
			destroy(proc);
		}

		return rv;
	}
	
	public static String exec_reply_daemon(String path, String cmd, long interval) {
		String inner_cmd = ShellEnv.SHELL_UPDATE_DAEMON_WORK + " '" + path + "' '" + cmd + "'";
		
		Process proc = null;
		String rv = "";
		try {
			proc = Runtime.getRuntime().exec(
					new String[] { "/bin/bash", "-c", inner_cmd });

			Thread.sleep(interval);
			
			rv = getNormalOutput(proc, false);

			proc.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			destroy(proc);
		}
		

		return rv;
	}
	
//	public static boolean exec_update_daemon_cmd(String path, String cmd, long interval, boolean debug) {
//		String inner_cmd = ShellEnv.SHELL_UPDATE_DAEMON_WORK + " '" + path + "' '" + cmd + "'";
//		
//		return exec(inner_cmd, interval, true);
//	}
	
	public static boolean exec_update_daemon_cmd(String path, String cmd, long interval, boolean debug) {
		String inner_cmd = ShellEnv.SHELL_UPDATE_DAEMON_WORK + " '" + path + "' " + cmd + "";
		
		return exec(inner_cmd, interval, true);
	}
	
	
	public static void destroy(Process proc) {
		if (proc != null) {
			try {
				proc.getErrorStream().close();
			} catch (IOException e) {
			}
			
			try {
				proc.getInputStream().close();
			} catch (IOException e) {
			}
			
			try {
				proc.getOutputStream().close();
			} catch (IOException e) {
			}
			
			proc.destroy();
		}
	}
	
	public static String[] crt_cmd(String shell) {
		String shells[] = shell.split(" ");
		
		List<String> cmd = new ArrayList<String>();
		
		String tmp = "";
		int index = 0;
		
		for (String s : shells) {
			if (s.trim().length() == 0) {
				continue;
			}
			
			if ((index == 0 && s.indexOf("'") == -1) || (s.startsWith("'") && s.endsWith("'"))) {
				cmd.add(s);
				continue;
			}else if (s.indexOf("'") == -1){
				tmp += s;
			}else{
				tmp += s;
				++index;
			}
			
			if (index == 1) {
				tmp += " ";
			} else if (index == 2) {
				cmd.add(tmp);
				index = 0;
				tmp = "";
			}
		}
		
		//return (String[])cmd.toArray();
		String rv[] = new String[cmd.size()];
		for (int i = 0; i < cmd.size(); i++) {
			rv[i] = cmd.get(i);
		}
		
		return rv;
			
	}

}

2、如何調用這個工具類如下

private boolean ftp_send(String ftp_addr, String remote_dir, String username, String password) {
		String cmd = ShellEnv.SHELL_FTP_SEND + " " + ftp_addr + " " + // FTP目標地址
				username + " " + // 目標主機用戶名
				password + " " + // 目標主機密碼
				PathEnv.OUTPUT_TASK + " " + // 本地路徑
				remote_dir + " " + // 目標路徑
				this.file_name + ".zip"; // 文件名
		boolean rv = ProcessTool.exec(cmd, true);
		return rv;
	}

或者

private void unzip_tmp_log_tar(String fileName) {
	String cmd = "tar xvfP /var/log/" + fileName;//shell腳本位置
	
	try {
	ProcessTool.exec(cmd, 50, true);
	} finally {
		File tmp = new File("/var/log/" + fileName);
		if (tmp.exists()) {
			tmp.delete();
		}
	}
}

 等等具體使用還是要看你調用工具類的哪個方法

 

發佈了70 篇原創文章 · 獲贊 1037 · 訪問量 49萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章