如何通过命令行识别云服务器使用的CentOS或Ubuntu版本?

可以通过以下命令识别云服务器的CentOS或Ubuntu版本:

1. 通用方法(适用于大多数Linux发行版)

查看发行版信息文件

# 查看 /etc/os-release 文件(推荐)
cat /etc/os-release

# 或查看 /etc/issue 文件
cat /etc/issue

# 或查看 /etc/issue.net 文件
cat /etc/issue.net

使用 lsb_release 命令

# 显示所有信息
lsb_release -a

# 只显示描述信息
lsb_release -d

# 只显示发行版ID
lsb_release -i

# 只显示版本号
lsb_release -r

2. 特定发行版的方法

对于CentOS/RHEL系统

# 查看CentOS版本
cat /etc/centos-release

# 查看Red Hat版本
cat /etc/redhat-release

# 查看系统版本(CentOS 7+)
hostnamectl

# 查看内核和架构信息
uname -a

对于Ubuntu/Debian系统

# 查看Ubuntu版本
cat /etc/lsb-release

# 查看Debian版本
cat /etc/debian_version

3. 快速判断脚本

可以创建一个简单的脚本一次性显示所有信息:

#!/bin/bash
echo "=== 系统信息 ==="
echo "1. /etc/os-release:"
cat /etc/os-release
echo ""
echo "2. lsb_release:"
lsb_release -a 2>/dev/null || echo "lsb_release未安装"
echo ""
echo "3. 发行版特定文件:"
[ -f /etc/centos-release ] && echo "CentOS: $(cat /etc/centos-release)"
[ -f /etc/redhat-release ] && echo "RHEL: $(cat /etc/redhat-release)"
[ -f /etc/lsb-release ] && echo "Ubuntu LSB: $(grep DESCRIPTION /etc/lsb-release)"
echo ""
echo "4. 内核版本:"
uname -r

4. 常用命令总结

命令 作用 适用系统
cat /etc/os-release 显示标准化的发行版信息 所有现代Linux
lsb_release -a 显示LSB标准信息 安装了lsb-core的系统
cat /etc/centos-release 显示CentOS版本 CentOS
cat /etc/lsb-release 显示Ubuntu版本信息 Ubuntu
hostnamectl 显示系统信息(CentOS 7+/Ubuntu 16.04+) systemd系统

5. 如果命令不存在

如果 lsb_release 不存在,可以安装:

  • CentOS/RHEL: yum install redhat-lsb-core -y
  • Ubuntu/Debian: apt-get install lsb-release -y

示例输出

CentOS示例:

$ cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"

Ubuntu示例:

$ cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04.3 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.3 LTS"
VERSION_ID="20.04"

推荐使用 cat /etc/os-release,这是最标准且通用的方法,适用于几乎所有现代Linux发行版。

云服务器