How To Execute Shell Command From Java

java-execute-shell-command

In Java, you can use Runtime.getRuntime().exec to execute external shell command :

    p = Runtime.getRuntime().exec("host -t a " + domain);
    p.waitFor();
 
    BufferedReader reader = 
         new BufferedReader(new InputStreamReader(p.getInputStream()));
 
    String line = "";			
    while ((line = reader.readLine())!= null) {
	sb.append(line + "\n");
    }


1. PING example

Classical example to execute the ping command and print out its output.

ExecuteShellComand.java


package com.mkyong.shell;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class ExecuteShellComand {
 
	public static void main(String[] args) {
 
		ExecuteShellComand obj = new ExecuteShellComand();
 
		String domainName = "google.com";
 
		//in mac oxs
		String command = "ping -c 3 " + domainName;
 
		//in windows
		//String command = "ping -n 3 " + domainName;
 
		String output = obj.executeCommand(command);
 
		System.out.println(output);
 
	}
 
	private String executeCommand(String command) {
 
		StringBuffer output = new StringBuffer();
 
		Process p;
		try {
			p = Runtime.getRuntime().exec(command);
			p.waitFor();
			BufferedReader reader = 
                            new BufferedReader(new InputStreamReader(p.getInputStream()));
 
                        String line = "";			
			while ((line = reader.readLine())!= null) {
				output.append(line + "\n");
			}
 
		} catch (Exception e) {
			e.printStackTrace();
		}
 
		return output.toString();
 
	}
 
}


Output

PING google.com (74.125.135.x): 56 data bytes
64 bytes from 74.125.135.x: icmp_seq=0 ttl=53 time=8.289 ms
64 bytes from 74.125.135.x: icmp_seq=1 ttl=53 time=7.733 ms
64 bytes from 74.125.135.x: icmp_seq=2 ttl=53 time=8.343 ms
 
--- google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 7.733/8.122/8.343/0.276 ms
null
2. HOST Example

Example to execute shell command host -t a google.com to get all the IP addresses that attached to google.com. Later, we use regular expression to grab all the IP addresses and display it.

P.S “host” command is available in *nix system only.

ExecuteShellComand.java

package com.mkyong.shell;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ExecuteShellComand {
 
	private static final String IPADDRESS_PATTERN = "([01]?\\d\\d?|2[0-4]\\d|25[0-5])" 
		+ "\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])" 
		+ "\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])" 
		+ "\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
 
	private static Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
	private static Matcher matcher;
 
	public static void main(String[] args) {
 
		ExecuteShellComand obj = new ExecuteShellComand();
 
		String domainName = "google.com";
		String command = "host -t a " + domainName;
 
		String output = obj.executeCommand(command);
 
		//System.out.println(output);
 
		List<String> list = obj.getIpAddress(output);
 
		if (list.size() > 0) {
			System.out.printf("%s has address : %n", domainName);
			for (String ip : list) {
				System.out.println(ip);
			}
		} else {
			System.out.printf("%s has NO address. %n", domainName);
		}
 
	}
 
	private String executeCommand(String command) {
 
		StringBuffer output = new StringBuffer();
 
		Process p;
		try {
			p = Runtime.getRuntime().exec(command);
			p.waitFor();
			BufferedReader reader = 
                           new BufferedReader(new InputStreamReader(p.getInputStream()));
 
			String line = "";			
			while ((line = reader.readLine())!= null) {
				output.append(line + "\n");
			}
 
		} catch (Exception e) {
			e.printStackTrace();
		}
 
		return output.toString();
 
	}
 
	public List<String> getIpAddress(String msg) {
 
		List<String> ipList = new ArrayList<String>();
 
		if (msg == null || msg.equals(""))
			return ipList;
 
		matcher = pattern.matcher(msg);
		while (matcher.find()) {
			ipList.add(matcher.group(0));
		}
 
		return ipList;
	}
}


Output

google.com has address : 
74.125.135.x
74.125.135.x
74.125.135.x
74.125.135.x
74.125.135.x
74.125.135.x
转自:http://www.mkyong.com/java/how-to-execute-shell-command-from-java/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值