使用Java程序本地执行Linux命令

两个程序:CommandTest执行Linux命令,将其打成jar包,放在服务器上面执行;SimpleTest是被CommandTest调用的命令执行的程序。
在这里插入图片描述

服务器上面文件的存放路径:
在这里插入图片描述

程序代码:CommandTest

public class CommandTest {
    
    

	public static List<String> getCommandList() {
    
    
		String path = "/home/huangqiqi/simpleTest";
		List<String> commands = new ArrayList<>();
		commands.add("cd " + path);
		commands.add("ls");
		commands.add("ulimit -c unlimited");
		commands.add("java -jar SimpleTest.jar > test.out");
		return commands;
	}

	public static void executeCommands(List<String> commands) throws IOException {
    
    
		for (String cmd : commands) {
    
    
			System.out.println("execute cmd : " + cmd);
		}
		Runtime run = Runtime.getRuntime();
		Process proc = null;
		BufferedReader in = null;
		PrintWriter out = null;
		boolean isDump = false;
		try {
    
    
			proc = run.exec("/bin/bash", null, null);
			in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
			for (String line : commands) {
    
    
				out.println(line);
			}
			out.println("exit");
			String line = "";
			while ((line = in.readLine()) != null) {
    
    
				System.out.println("readLine: " + line);
				if (line.indexOf("core.") >= 0) {
    
    
					isDump = true;
					break;
				}
			}
			proc.waitFor();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			if (proc != null)
				proc.destroy();
			if (in != null)
				in.close();
			if (out != null)
				out.close();
		}
		if (isDump) {
    
    
			System.exit(0);
		}
	}

	public static void main(String[] args) {
    
    
		List<String> commands = getCommandList();
		try {
    
    
			executeCommands(commands);
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}

	}

}

程序代码:SimpleTest 类:

public class SimpleTest {
    
    

	public static void main(String[] args) {
    
    
		for (int i = 0; i < 10; i++) {
    
    
			System.out.println("Hello World: " + i);
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_42570601/article/details/117373581
今日推荐