大家好:
最近在做一些Java操作Linux的配置功能。目前功能未测试,只做自己的备份处理。备份下实现类。
package com.yltd.sams.service.settings.general.impl;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yltd.sams.service.settings.general.NetworkSettingsService;
import com.yltd.sams.service.shell.ShellService;
import lombok.extern.slf4j.Slf4j;
/**
* 系统设置 > 通用设置-网络设置
* @author zhangyixin
* @date 2020/04/13
*/
@Slf4j
@Service
public class NetworkSettingsServiceImpl implements NetworkSettingsService {
@Autowired
private ShellService shellService;
/**
* 获取Linux下的IP地址-ipv4
*
* @return IP地址
* @throws SocketException
*/
@Override
public String getLinuxLocalIp() throws SocketException {
String ip = "";
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
ip = ipaddress;
log.info("============================" +ip);
}
}
}
}
}
} catch (SocketException ex) {
log.info("============================");
ip = "127.0.0.1";
ex.printStackTrace();
}
System.out.println("IP:"+ip);
return ip;
}
/**
* 获取Linux下的IP地址-ipv6
* @return
*/
@Override
public String getLocalIPv6Address() throws IOException {
InetAddress inetAddress = null;
Enumeration networkInterfaces = NetworkInterface
.getNetworkInterfaces();
outer:
while (networkInterfaces.hasMoreElements()) {
Enumeration inetAds = networkInterfaces.nextElement()
.getInetAddresses();
while (inetAds.hasMoreElements()) {
inetAddress = inetAds.nextElement();
//Check if it's ipv6 address and reserved address
if (inetAddress instanceof Inet6Address
&& !isReservedAddr(inetAddress)) {
break outer;
}
}
}
String ipAddr = inetAddress.getHostAddress();
// Filter network card No
int index = ipAddr.indexOf('%');
if (index > 0) {
ipAddr = ipAddr.substring(0, index);
}
return ipAddr;
}
/**
* 判断Linux下的IP地址-ipv6 是否正确
* @param inetAddr
* @return
*/
private boolean isReservedAddr(InetAddress inetAddr) {
if (inetAddr.isAnyLocalAddress() || inetAddr.isLinkLocalAddress()
|| inetAddr.isLoopbackAddress()) {
return true;
}
return false;
}
/**
* 获取Linux本地-子网掩码
* @return
*/
@Override
public String getLinuxLocalNi() throws SocketException {
InetAddress ip = null;
NetworkInterface ni = null;
String net ="";
try {
ip = InetAddress.getLocalHost();
ni = NetworkInterface.getByInetAddress(ip);// 搜索绑定了指定IP地址的网络接口
List list = ni.getInterfaceAddresses();// 获取此网络接口的全部或部分
// InterfaceAddresses
// 所组成的列表
if (list.size() > 0) {
int mask = list.get(0).getNetworkPrefixLength(); // 子网掩码的二进制1的个数
StringBuilder maskStr = new StringBuilder();
int[] maskIp = new int[4];
for (int i = 0; i < maskIp.length; i++) {
maskIp[i] = (mask >= 8) ? 255 : (mask > 0 ? (mask & 0xff) : 0);
mask -= 8;
maskStr.append(maskIp[i]);
if (i < maskIp.length - 1) {
maskStr.append(".");
}
}
System.out.println("SubnetMask:" + maskStr);
net = maskStr.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return net;
}
/**
* 获取Linux本地-网关
* @return
*/
@Override
public String getgateway() throws SocketException {
String[] cmd = new String[] { "/bin/sh","-c", "route | grep -P \"^default.*eth0$\" | awk '{print $2}'" };
String gateway = null;
Process process;
try {
process = Runtime.getRuntime().exec(cmd);
InputStreamReader r = new InputStreamReader(process.getInputStream());
LineNumberReader returnData = new LineNumberReader(r);
gateway = returnData.readLine();
System.out.println("网关"+gateway);
log.info("============================" +gateway);
} catch (IOException ex) {
log.info("============================");
ex.printStackTrace();
}
return gateway;
}
/**
* 更新Linux下的IP地址-ipv4
*/
@Override
public String updateIPV4(Map map) throws IOException {
String flage ="";
try {
Runtime.getRuntime().exec("mv /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/network-scripts/ifcfg-eth0_bak");
String IPADDR = "IPADDR="+map.get("IPv4")+"\n"; //ip地址
String NETMASK = "NETMASK="+map.get("IPv4Net")+"\n"; //子网掩码
String NETWORK="NETWORK="+map.get("IPv4Gateway")+"\n";//网关地址
BufferedReader reader = new BufferedReader(new FileReader("/etc/sysconfig/network-scripts/ifcfg-eth0_bak"));
BufferedWriter in = new BufferedWriter(new FileWriter(new File("/etc/sysconfig/network-scripts/ifcfg-eth0")));
String line=null;
boolean identify_ip = false;
boolean identify_ma = false;
boolean identify_wo = false;
while ((line=reader.readLine())!=null) {
if(line!=null && line.length()>0 && line.startsWith("IPADDR=")){
in.write(IPADDR);
identify_ip=true;
}else if(line!=null && line.length()>0 && line.startsWith("NETMASK=")){
in.write(NETMASK);
identify_ma=true;
}else if(line!=null && line.length()>0 && line.startsWith("NETWORK=")){
in.write(NETWORK);
identify_wo=true;
}else{
in.write(line);
}
}
if(!identify_ip &&!identify_ma &&!identify_wo){
in.write(IPADDR);
in.write(NETMASK);
in.write(NETWORK);
}
//关闭流,不可以少,否则数据在缓存,没有实际写入
reader.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return flage;
}
/**
* 获取Linux下的IP地址-ipv6
* @return
*/
@Override
public String updateIPV6(Map map) throws IOException {
String flage ="";
try {
//查询是否存在 - 打开/关闭网络配置
Runtime.getRuntime().exec("mv /etc/sysconfig/network /etc/sysconfig/network_bak");
String NETWORKING_IPV6 = "NETWORKING_IPV6=yes";//打开IPv6
String IPV6_AUTOCONF = "IPV6_AUTOCONF=no";//不自动获取地址,即:设置"no”
BufferedReader reader = new BufferedReader(new FileReader("/etc/sysconfig/network_bak"));
BufferedWriter in = new BufferedWriter(new FileWriter(new File("/etc/sysconfig/network")));
String line=null;
boolean identify = false;
boolean identifying = false;
while ((line=reader.readLine())!=null) {
if(line!=null && line.length()>0 && line.startsWith("NETWORKING_IPV6")){
in.write(NETWORKING_IPV6);
identify = true;
}else if(line!=null && line.length()>0 && line.startsWith("IPV6_AUTOCONF")){
in.write(IPV6_AUTOCONF);
identifying = true;
}else{
in.write(line);
}
}
if(!identify &&!identifying){//如果未查询到已存在的,就添加相关数据
in.write(NETWORKING_IPV6); //写入打开IPv6
in.write(IPV6_AUTOCONF);//写入不自动获取地址,即:设置"no”
}
//关闭流,不可以少,否则数据在缓存,没有实际写入
reader.close();
in.close();
//配置IP/IPv6地址,网关等
Runtime.getRuntime().exec("mv /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/network-scripts/ifcfg-eth0_bak");
String IPV6ADDR = "IPV6INIT=yes\nIPV6ADDR="+map.get("IPv6")+"\n";//配置IPv6地址
String IPV6_DEFAULTGW = "IPV6_DEFAULTGW="+map.get("IPv6Gateway")+"\n";//配置IPv6网关
BufferedReader readerFile = new BufferedReader(new FileReader(" /etc/sysconfig/network-scripts/ifcfg-eth0_bak"));
BufferedWriter inFile = new BufferedWriter(new FileWriter(new File(" /etc/sysconfig/network-scripts/ifcfg-eth0")));
String lineFile=null;
boolean identifyFile = false;
boolean identifyingLile = false;
while ((lineFile=readerFile.readLine())!=null) {
if(lineFile!=null && lineFile.length()>0 && lineFile.startsWith("IPV6ADDR")){
inFile.write(IPV6ADDR);
identify = true;
}else if(lineFile!=null && lineFile.length()>0 && lineFile.startsWith("IPV6_DEFAULTGW")){
inFile.write(IPV6_DEFAULTGW);
identifying = true;
}else{
inFile.write(lineFile);
}
}
if(!identifyFile &&!identifyingLile){//如果未查询到已存在的,就添加相关数据
inFile.write(IPV6ADDR); //写入配置IPv6地址
inFile.write(IPV6_DEFAULTGW);//写入配置IPv6网关
}
//关闭流,不可以少,否则数据在缓存,没有实际写入
readerFile.close();
inFile.close();
//重启服务
Runtime.getRuntime().exec("service network restart");
} catch (Exception e) {
e.printStackTrace();
}
return flage;
}
//=====================================查询系统已经运行的 时间 的实现================
/**
* 获取linux命令执行的结果,cat 之类
* @param cmd
* @return
*/
public String getCmdResult(String cmd) {
String result = "";
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStreamReader ir = new InputStreamReader(process.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null){
result=line;
}
}
catch (java.io.IOException e) {
log.info("============================"+e);
System.err.println("IOException " + e.getMessage());
}
return result;
}
/**
* 返回运行时间:天数+小时
* @return
*/
public String getUptime(String str){
String time=null;
if(str.contains(",")){
String [] strArr=str.split(",");
if(strArr.length>2){
int hms=0;
String day="";
int hours=0;
if(str.contains("days")){
//截取到天
day=strArr[0].substring(strArr[0].indexOf("up")+2,strArr[0].indexOf("days")).trim();
//时分秒的秒数
hms=Integer.parseInt(getHms(strArr[1].replace("min","").trim()));
//将秒数转换成小时数
hours = (hms % ( 60 * 60 * 24)) / (60 * 60);
}else if(str.contains("day")){
//截取到天
day=strArr[0].substring(strArr[0].indexOf("up")+2,strArr[0].indexOf("day")).trim();
//时分秒的秒数
hms=Integer.parseInt(getHms(strArr[1].replace("min","").trim()));
//将秒数转换成小时数
hours = (hms % ( 60 * 60 * 24)) / (60 * 60);
}else{
String hmsStr=strArr[0].substring(strArr[0].indexOf("up")+2);
hms=Integer.parseInt(getHms(hmsStr.replace("min","").trim()));
//将秒数转换成小时数
hours = (hms % ( 60 * 60 * 24)) / (60 * 60);
}
time= day+"天"+hours+"个小时";
}
}
return time;
}
/**
* 返回运行时间的秒数
* @return
*/
public String getUptimeSecond(String str){
String time=null;
if(str.contains(",")){
String [] strArr=str.split(",");
if(strArr.length>2){
int hms=0;
int days=0;
if(str.contains("days")){
//截取到天
String day=strArr[0].substring(strArr[0].indexOf("up")+2,strArr[0].indexOf("days")).trim();
//天的秒数
days=Integer.parseInt(day) * 24 * 3600;
//时分秒的秒数
hms=Integer.parseInt(getHms(strArr[1].replace("min","").trim()));
}
else if(str.contains("day")){
//截取到天
String day=strArr[0].substring(strArr[0].indexOf("up")+2,strArr[0].indexOf("day")).trim();
//天的秒数
days=Integer.parseInt(day) * 24 * 3600;
//时分秒的秒数
hms=Integer.parseInt(getHms(strArr[1].replace("min","").trim()));
}
else{
String hmsStr=strArr[0].substring(strArr[0].indexOf("up")+2);
hms=Integer.parseInt(getHms(hmsStr.replace("min","").trim()));
}
Integer totalTime=days+hms;
time=totalTime.toString();
}
}
return time;
}
/**
* 获取中间字段的秒数
* @param str
* @return
*/
public String getHms(String str){
String result=null;
Integer hms=0;
if(str.contains(":")){
String [] hmsArr=str.split("\\:");
int length=hmsArr.length;
switch (length){
//只有秒
case 1:hms+=Integer.parseInt(hmsArr[0]);
break;
//时分
case 2:hms+=(Integer.parseInt(hmsArr[0]) * 3600 + Integer.parseInt(hmsArr[1]) *60);
break;
//时分秒
case 3:hms+=(Integer.parseInt(hmsArr[0]) * 3600 + Integer.parseInt(hmsArr[1]) *60 +Integer.parseInt(hmsArr[2]));
break;
}
}
else{
//不包含: 只能是分
hms+=Integer.parseInt(str) * 60;
}
if(hms>0){
result=hms.toString();
}
return result;
}
/**
* 获取运行时间
* @return
*/
@Override
public String getRouterUptime(){
return getUptime(getCmdResult("uptime"));
}
/**
* 获取路由表list
* @return
* @throws Exception
*/
@Override
public String getRoutList() throws Exception {
return shellService.execShell("netstat -rn");
}
/**
* 删除指定的路由表
* -net:目标地址是一个网络。
* netmask:当添加一个网络路由时,需要使用网络掩码。
* gw:路由数据包通过网关。注意,你指定的网关必须能够达到。网关,又称下一跳路由器
* @return
* @throws Exception
*/
@Override
public String delectRout(Map map) throws Exception{
//route del -net 192.168.9.112 netmask 1.0.0.0 gw 1.1.1.1
String sentence="route del -net "+map.get("destinationAddress")+" netmask "+map.get("netMask")+" gw "+map.get("nextJump");
return shellService.execShell(sentence);
}
/**
* 添加指定的路由表
* -net:目标地址是一个网络。
* netmask:当添加一个网络路由时,需要使用网络掩码。
* gw:路由数据包通过网关。注意,你指定的网关必须能够达到。网关,又称下一跳路由器
* @return
* @throws Exception
*/
@Override
public String addRout(Map map) throws Exception{
//route del -net 192.168.9.112 netmask 1.0.0.0 gw 1.1.1.1
String sentence="route add -net "+map.get("destinationAddress")+" netmask "+map.get("netMask")+" gw "+map.get("nextJump");
return shellService.execShell(sentence);
}
/**
* 查询dns
* cat /etc/resolv.conf
*/
@Override
public String getDNS(Map map) throws Exception {
return shellService.execShell("cat /etc/resolv.conf");
}
}
package com.yltd.sams.service.shell.impl;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.springframework.stereotype.Service;
import com.yltd.sams.service.shell.ShellService;
@Service
public class ShellServiceImpl implements ShellService{
@Override
public String execShell(String cmdstring) throws Exception{
Process proc = Runtime.getRuntime().exec(cmdstring);
// 注意下面的操作
String ls_1;
String ss = "";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ((ls_1 = bufferedReader.readLine()) != null) {
if (!"".equals(ss))
ss += "\n";
ss += ls_1;
}
bufferedReader.close();
proc.waitFor();
return ss;
}
@Override
public String uptime() throws Exception{
//08:34:29 up 21 days, 5:46, 1 user, load average: 0.06, 0.04, 0.00
String cmdRet = execShell("uptime");
//TODO: 处理命令返回情况
return cmdRet;
}
@Override
public String shutdown() throws Exception{
return execShell("shutdown -h now");
}
@Override
public String reboot() throws Exception{
return execShell("reboot");
}
}