当前位置: 首页 > news >正文

Centos Ubuntu RedOS系统类型下查看系统信息

在这里插入图片描述

文章目录

  • 一、项目背景
  • 二、页面
  • 三、说明
  • 四、代码
    • 1.SysInfo
    • 2.EmsSysConfig
    • 3.HostInformationController
    • 4.HostInfo

一、项目背景

公司项目想展示当前部署系统的:操作系统,软件版本、IP、主机名。

二、页面

在这里插入图片描述

三、说明

说明点1:查询系统类型及IP实际流程是,程序执行linux命令获取结果信息的过程。

说明点2:查询系统类型命令

hostnamectl | awk -F': +' '/Static hostname|Operating System/ {printf "%s,", $2}' | sed 's/,$//'

说明点3:目前项目支持查询3种不同类型的系统:Centos、Ubuntu、Res OS

说明点4:其中ip、os和hostname是从服务器查询出来的;version是从配置文件或者适配包读取的;

说明点5:IP其实是从网络接口中获取的信息,比如linux执行iFconfig即可获取网络接口信息,在每个接口的输出中,inet 行表示该接口的 IPv4 地址,inet6 行表示 IPv6 地址

CentOS 系统

  • 常见命名
    • 传统上使用 ethX(如 eth0, eth1)
    • 新版本(如 CentOS 7 及以上)可能使用 enoX 或 ensX 这样的命名方式。

Ubuntu 系统

  • 常见命名:
    • 新版本的 Ubuntu 通常使用 enpX(如 enp0s3, enp0s8)。

Red Hat 系统

  • 常见命名:
    • 新版本的 Red Hat 和 Fedora 系统通常使用 ensX(如 ens33, ens160)。

结论:

  • 对于 CentOS,你可以检查 eth, eno, 和 ens 开头的接口。
  • 对于 Ubuntu,检查 enp 开头的接口。
  • 对于 Red Hat 和 Fedora,检查 ens 开头的接口。

这种方式可以确保你能够捕获到常见的网络接口命名,并获取相应的 IPv4 地址。

四、代码

1.SysInfo

package com.hero.lte.ems.sysconf.model;import javax.xml.bind.annotation.XmlAttribute;/*** ems系统基本信息** @author w17231* @date 2017年4月13日*/
public class SysInfo {/*** ems对外通信IP*/private String emsCommIp;/*** ems系统IP*/private String emsSysIp;/*** 系统语言*/private String locale;/*** 产品名称*/private String productName;/*** 进程名称*/private String processName;/*** 产品版本*/private String productVersion;private String ftpRootPath;private String ftpUploadPath;private String verification;private String ftpPatchPath;/*** 制造商*/private String manufacturer;/*** 产品描述*/private String description;private String systemVersion;private String systemRoot;public String getEmsCommIp() {return emsCommIp;}public void setEmsCommIp(String emsCommIp) {this.emsCommIp = emsCommIp;}public String getEmsSysIp() {return emsSysIp;}public void setEmsSysIp(String emsSysIp) {this.emsSysIp = emsSysIp;}public String getLocale() {return locale;}public void setLocale(String locale) {this.locale = locale;}public String getProductName() {return productName;}public void setProductName(String productName) {this.productName = productName;}@XmlAttributepublic String getProductVersion() {return productVersion;}public void setProductVersion(String productVersion) {this.productVersion = productVersion;}public String getManufacturer() {return manufacturer;}public void setManufacturer(String manufacturer) {this.manufacturer = manufacturer;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getProcessName() {return processName;}public void setProcessName(String processName) {this.processName = processName;}public String getFtpRootPath() {return ftpRootPath;}public void setFtpRootPath(String ftpRootPath) {this.ftpRootPath = ftpRootPath;}public String getFtpUploadPath() {return ftpUploadPath;}public void setFtpUploadPath(String ftpUploadPath) {this.ftpUploadPath = ftpUploadPath;}public String getVerification() {return verification;}public void setVerification(String verification) {this.verification = verification;}public String getSystemVersion() {return systemVersion;}public void setSystemVersion(String systemVersion) {this.systemVersion = systemVersion;}public String getSystemRoot() {return systemRoot;}public void setSystemRoot(String systemRoot) {this.systemRoot = systemRoot;}public String getFtpPatchPath() {return ftpPatchPath;}public void setFtpPatchPath(String ftpPatchPath) {this.ftpPatchPath = ftpPatchPath;}@Overridepublic String toString() {return "SysInfo{" +"emsCommIp='" + emsCommIp + '\'' +", emsSysIp='" + emsSysIp + '\'' +", locale='" + locale + '\'' +", productName='" + productName + '\'' +", processName='" + processName + '\'' +", productVersion='" + productVersion + '\'' +", ftpRootPath='" + ftpRootPath + '\'' +", ftpUploadPath='" + ftpUploadPath + '\'' +", ftpPatchPath='" + ftpPatchPath + '\'' +", verification='" + verification + '\'' +", manufacturer='" + manufacturer + '\'' +", description='" + description + '\'' +", systemVersion='" + systemVersion + '\'' +", systemRoot='" + systemRoot + '\'' +'}';}
}

2.EmsSysConfig

package com.hero.lte.ems.configuration;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hero.lte.ems.sysconf.model.InstallInfo;
import com.hero.lte.ems.sysconf.model.SysInfo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;@Configuration
public class EmsSysConfig {@Bean(name = "sysInfo")public SysInfo getSysInfo() {SysInfo sysInfo = new SysInfo();DynamicConfig dynamicConfig = DynamicConfigLoader.load("server.properties");sysInfo.setEmsCommIp(dynamicConfig.getString("system.transport.ip"));sysInfo.setEmsSysIp(dynamicConfig.getString("service.host"));sysInfo.setProcessName(dynamicConfig.getString("service.name"));sysInfo.setProductName(dynamicConfig.getString("service.productName"));sysInfo.setSystemVersion(dynamicConfig.getString("service.version"));sysInfo.setFtpRootPath(dynamicConfig.getString("system.ftprootpath"));sysInfo.setFtpUploadPath(dynamicConfig.getString("system.uploadpath"));sysInfo.setFtpPatchPath(dynamicConfig.getString("system.ftppatchpath"));sysInfo.setLocale(dynamicConfig.getString("system.language"));sysInfo.setVerification(dynamicConfig.getString("verification"));sysInfo.setSystemRoot(dynamicConfig.getString("system.root"));return sysInfo;}

3.HostInformationController

package com.hero.lte.ems.sysmanager.resources;import com.hero.lte.ems.common.spring.SpringContextHolder;
import com.hero.lte.ems.sysconf.model.SysInfo;
import com.hero.lte.ems.sysmanager.entity.HostInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@RestController
@RequestMapping(value = "lte/ems/sysmanager/host")
@Api(value = "HostInformationController",tags={"系统信息"})
public class HostInformationController {private static Logger logger = LoggerFactory.getLogger(HostInformationController.class);public static String CENTOS_SYSTEM = "CentOS";public static String UBUNTU_SYSTEM = "Ubuntu";public static String REDOS_SYSTEM = "RED OS";@RequestMapping(value = "info", method = RequestMethod.GET)@ApiOperation("系统信息")public HostInfo getMailConfig() throws Exception{SysInfo sysInfo = SpringContextHolder.getBean(SysInfo.class);List<String> list = getAllHostIp();final StringBuilder ip = new StringBuilder("");if(list!=null&&list.size()>0){list.forEach(o->{ip.append(o+"/");});ip.deleteCharAt(ip.length()-1);}HostInfo hostInfo = new HostInfo();//hostInfo.setIp(sysInfo.getEmsCommIp());Map<String, String> map = getHostnameAndSystem();hostInfo.setIp(ip.toString());hostInfo.setVersion(sysInfo.getSystemVersion());hostInfo.setHostname(map.get("hostname").equals("n/a") ? "localhost" : map.get("hostname"));hostInfo.setOs(map.get("os"));return hostInfo;}public Map<String, String> getHostnameAndSystem() {Map<String, String> map = new HashMap<>();InputStream in = null;BufferedReader read = null;Process pro = null;String cmd = "hostnamectl | awk -F': +' '/Static hostname|Operating System/ {printf \"%s,\", $2}' | sed 's/,$//'";String[] cmds = null;try {String result = getSingleResult(cmd, cmds, pro, in, read);logger.info("result:{}", result);String[] split = result.split(",");map.put("hostname", split[0]);map.put("os", split[1]);} catch (IOException | InterruptedException e) {logger.error("-getHostnameAndSystem-Exception:{}", e);return null;} finally {try {if (pro != null) {pro.destroy();}if (read != null) {read.close();}if (in != null) {in.close();}} catch (IOException e) {logger.error("-getHostnameAndSystem-finally-IOException:{}", e);}}return map;}public static String getSingleResult(String cmd, String[] cmds, Process pro, InputStream in, BufferedReader read) throws IOException, InterruptedException {cmds = new String[]{"/bin/sh", "-c", cmd};logger.info("-cmd:{}", cmd);pro = Runtime.getRuntime().exec(cmds);if (pro.waitFor() == 0) {String line = "";in = pro.getInputStream();read = new BufferedReader(new InputStreamReader(in));while ((line = read.readLine()) != null) {logger.info("-line:{}", line);return line;}}return null;}/*** 获取该主机上所有网卡的ip*/public static ArrayList<String> getAllHostIp(){ArrayList<String> hostAddress = new ArrayList<>();try{String systemType = createSystemMonitor();// 获得本机的所有网络接口Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();while (nifs.hasMoreElements()) {NetworkInterface nif = nifs.nextElement();//查询Centos系统参数if(systemType.equals(CENTOS_SYSTEM) && nif.getName().startsWith("eth") || nif.getName().startsWith("eno")) {// 获得与该网络接口绑定的 IP 地址,一般只有一个Enumeration<InetAddress> addresses = nif.getInetAddresses();while (addresses.hasMoreElements()) {InetAddress addr = addresses.nextElement();if (addr instanceof Inet4Address) { // 只关心 IPv4 地址hostAddress.add(addr.getHostAddress());}}} else if(systemType.equals(UBUNTU_SYSTEM) && nif.getName().startsWith("enp")) {//查询ubuntu系统参数,获得与该网络接口绑定的 IP 地址,一般只有一个Enumeration<InetAddress> addresses = nif.getInetAddresses();while (addresses.hasMoreElements()) {InetAddress addr = addresses.nextElement();if (addr instanceof Inet4Address) { // 只关心 IPv4 地址hostAddress.add(addr.getHostAddress());}}} else if(systemType.equals(REDOS_SYSTEM) && nif.getName().startsWith("ens")) {logger.info("nif.getName():{}", nif.getName());//查询redos系统参数,获得与该网络接口绑定的 IP 地址,一般只有一个Enumeration<InetAddress> addresses = nif.getInetAddresses();while (addresses.hasMoreElements()) {InetAddress addr = addresses.nextElement();if (addr instanceof Inet4Address) {hostAddress.add(addr.getHostAddress());}}}}}catch(Exception e){e.printStackTrace();}return hostAddress;}public static String createSystemMonitor() {String systemType = "";InputStream in = null;BufferedReader read = null;Process pro = null;String cmd = "hostnamectl | awk -F': +' '/Static hostname|Operating System/ {printf \"%s,\", $2}' | sed 's/,$//'";String[] cmds = null;try {String result = getSingleResult(cmd, cmds, pro, in, read);String[] split = result.split(",");String os = split[1];if (os.contains(CENTOS_SYSTEM)) {systemType = CENTOS_SYSTEM;} else if (os.contains(UBUNTU_SYSTEM)) {systemType = UBUNTU_SYSTEM;} else if (os.contains(REDOS_SYSTEM)) {systemType = REDOS_SYSTEM;}} catch (IOException | InterruptedException e) {logger.error("-createSystemMonitor-Exception:{}", e);return null;} finally {try {if (pro != null) {pro.destroy();}if (read != null) {read.close();}if (in != null) {in.close();}} catch (IOException e) {logger.error("-createSystemMonitor-finally-IOException:{}", e);}}return systemType;}}

4.HostInfo

package com.hero.lte.ems.sysmanager.entity;public class HostInfo {private String os = "CentOS Linux release 7.7.1908 (Core)";;private String version;private String ip;private String hostname = "localhost.localdomain";public String getOs() {return os;}public void setOs(String os) {this.os = os;}public String getVersion() {return version;}public void setVersion(String version) {this.version = version;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getHostname() {return hostname;}public void setHostname(String hostname) {this.hostname = hostname;}@Overridepublic String toString() {return "HostInfo{" +"os='" + os + '\'' +", version='" + version + '\'' +", ip='" + ip + '\'' +", hostname='" + hostname + '\'' +'}';}
}

相关文章:

  • TiDB 可观测性最佳实践
  • 【深度解析】YOLOE登场:CNN路线的开放世界新答卷,超越YOLO-World与Transformer
  • 华为云Astro大屏从iotda影子设备抽取数据做设备运行状态的大屏实施步骤
  • 故障诊断——复现github代码ClassBD-CNN(BDCNN)
  • React Navigation 使用指南
  • 高翔《视觉SLAM十四讲》第七章视觉里程计3d-2d位姿估计代码详解与理论解析
  • Go语言中的 `time.Tick` 函数详解
  • 【AI提示词】机会成本决策分析师
  • Ubuntu搭建 Nginx以及Keepalived 实现 主备
  • Python数据处理:文件的自动化重命名与整合
  • jmeter-Beashell获取请求body data
  • 【统计方法】交叉验证:Resampling, nested 交叉验证等策略 【含R语言】
  • 【go】defer捕获panic案例,自存档
  • .NET 平台详解
  • 什么是DNS缓存?怎么清理DNS缓存?
  • 从数据到决策:安科瑞EIoT如何让每一度电“清晰可见”?
  • SpringMVC再复习1
  • 元宇宙2.0:当区块链成为数字世界的宪法
  • 阿里云服务器 篇十二:加入 Project Honey Pot 和使用 http:BL
  • Scrapy框架之CrawlSpider爬虫 实战 详解
  • 五万吨级半潜船在沪完成装备装载
  • 知名计算机专家、浙江大学教授张森逝世
  • 俄罗斯称已收复库尔斯克州
  • 新城市志|中国消费第一城,迎来“补贴力度最大”购物节
  • 第三款在美获批的国产PD-1肿瘤药来了,影响多大?
  • 美联储官员:货币政策不会立即改变,金融市场波动或致美国经济增长承压