About using java to execute shell script to obtain the hard disk serial number and mac address of centos

1. Get the hard disk serial number:

Create a new shell script file: identifier.sh, the content is:

1 diskdata=`fdisk -l`
2 diskleft=${diskdata#*"identifier: "}
3 identifier=${diskleft%%" Device Boot"*}
4 echo ${identifier}

Adjust the permissions of identifier.sh:

1 chmod +x identifier.sh

Use Java code to call the shell script to get the result

 1 private static String getIdentifier() throws Exception {
 2     String path = "/usr/local/webapp/identifier.sh";
 3     Process process = Runtime.getRuntime().exec(path);
 4     process.waitFor();
 5 
 6     BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
 7     StringBuffer sb = new StringBuffer();
 8     String line;
 9     while ((line = br.readLine()) != null){
10         sb.append(line);
11     }
12     String str = sb.toString();
13     return str;
14 }

 

2. Get the MAC address:

Create a new shell script file: macAddress.sh, the content is:

1 macAddress=`ifconfig | awk -F'[ :]+' '!NF{if(eth!=""&&ip=="")print eth;eth=ip4=""}/^[^ ]/{eth=$1}/inet addr:/{ip=$4}'`
2 ifconfig ${macAddress[1]} | grep "ether" | awk '{print $2}'

Adjust the permissions of macAddress.sh:

1 chmod +x macAddress.sh

Use Java code to call the shell script to get the result

 1 private static String getMACAddress() throws Exception {
 2     String path = "/usr/local/webapp/macAddress.sh";
 3     Process process = Runtime.getRuntime().exec(path);
 4     process.waitFor();
 5 
 6     BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
 7     StringBuffer sb = new StringBuffer();
 8     String line;
 9     while ((line = br.readLine()) != null){
10         sb.append(line);
11     }
12     String str = sb.toString();
13     return str;
14 }

===============================================

test:

 1 public static void main(String[] args) throws Exception {
 2 
 3     System.out.println("==========kaishi==========");
 4     String macAddress = getMACAddress();
 5     System.out.println("macAddress is: " + macAddress);
 6     
 7     String identifier = getIdentifier();
 8     System.out.println("identifier is: " + identifier);
 9     
10     String uniquelyID = macAddress + "_" + identifier;
11     System.out.println("uniquelyID is: " + uniquelyID);
12     System.out.println("==========jieshu==========");
13 
14 }

===============================================

output:

=========kaishi==========
macAddress is: 00:0c:29:d2:ef:3e
identifier is: 0x0009c6b1
uniquelyID is: 00:0c:29:d2: ef:3e_0x0009c6b1
==========jieshu==========

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325188307&siteId=291194637