首先:
查看服务器版本,如果是centos,查看命令是:
cat /etc/centos-release
返回结果,如:
CentOS Linux release 7.5.1804 (Core)
1.找到网卡
2.代码读取:
(1)工具类
public class PropertyUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
private static Properties props=null;
synchronized static public HashMap<String, String> loadProps(String prop){
HashMap<String, String> map = new HashMap<>();
props = new Properties();
try {
props.load(loadConfig(prop));//读取文件
} catch (Exception e) {
e.printStackTrace();
}
for(Object i:props.keySet()){
map.put((String)i,props.getProperty((String)i));
}
return map;
}
//读取文件
public static InputStream loadConfig(String filename){
try {
InputStream ins;
String filePath =filename;
if (new File(filePath).exists()) {
System.err.println("Load Config file"+filePath);
ins = new BufferedInputStream(new FileInputStream(filePath));
} else {
System.err.println("Load Config file"+filename);
// System.out.println(PropertyUtil.class.get);
ins = PropertyUtil.class.getResourceAsStream(filename);
}
return ins;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//修改文件
public static void writeNetWorkCard(Map<String, String> netMap) {
String profilepath ="/etc/sysconfig/network-scripts/ifcfg-eno1";
logger.info("修改properties文件内容.......");
try {
for(String keyname : netMap.keySet()){
String keyvalue = netMap.get(keyname);
OutputStream fos = new FileOutputStream(profilepath);
props.setProperty(keyname, keyvalue);
props.store(fos, null);
fos.close();
}
} catch (IOException e) {
System.err.println("属性文件更新错误");
}
}
}
获取和修改网卡-配置调用代码:
(1)controller:
HashMap<String, String> ifcfgMap=sysService.getNetWorkCard();
把这个ifcfgmap return给前端。
(3)service:
/**
* 获取网卡信息
*/
public HashMap<String, String> getNetWorkCard(){
String profilepath="/etc/sysconfig/network-scripts/ifcfg-eno1";
HashMap<String, String> map= PropertyUtil.loadProps(profilepath);
return map;
}
/**
* 修改网卡信息
*/
public int updateNetWorkCard(Map<String, String> maps){
//1.修改
PropertyUtil.writeNetWorkCard(maps);
//2.执行重启网卡命令
String order="service network restart";
execCmd(order);
return 0;
}
/**
* cmd执行命令
*/
private String execCmd(String cmd){
StringBuilder sb=new StringBuilder();
try {
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line="";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch(Exception e1) {}
return sb.toString();
}