python 探测远端服务器操作系统是否是 linux 并获取其系统版本和系统架构 不使用 lsb_release

本文介绍了一种在远程服务器未安装lsb-release包时,通过Python脚本读取/etc/os-release和uname-m命令获取Linux发行版、版本及架构信息的方法,包括nmap和paramiko库的使用以及错误处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果远程服务器未安装lsb-release包,导致无法使用lsb_release -ds命令获取系统发行版及版本信息,您可以采用以下替代方法来获取这些信息:

  1. 读取 /etc/os-release 文件:大多数现代Linux发行版会在/etc/os-release文件中存储系统发行版和版本信息。您可以通过SSH连接到远程服务器并读取该文件的内容。

以下是修改后的Python脚本,不再使用lsb_release命令,而是直接读取/etc/os-release文件:

 

python

import nmap
import paramiko

def detect_remote_os(ip_address):
    nm = nmap.PortScanner()
    nm.scan(ip_address, arguments='-O')

    try:
        os_details = nm[ip_address]['osmatch'][0]
        os_name = os_details['name']
        os_accuracy = os_details['accuracy']
        
        return os_name, os_accuracy
    except KeyError:
        return None, None

def is_linux_os(os_name):
    return 'linux' in os_name.lower()

def get_remote_system_info(ip_address, username, password):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip_address, username=username, password=password)

    try:
        # 获取系统发行版及版本信息
        stdin, stdout, stderr = ssh.exec_command('cat /etc/os-release')
        os_release_content = stdout.read().decode()
        
        # 解析 /etc/os-release 文件内容
        distro_info = {}
        for line in os_release_content.split('\n'):
            if '=' in line:
                key, value = line.strip().split('=', 1)
                distro_info[key] = value.strip('"').strip("'")

        distro_name = distro_info.get('NAME', '')
        distro_version = distro_info.get('VERSION', '')

        # 获取系统架构信息
        stdin, stdout, stderr = ssh.exec_command('uname -m')
        arch = stdout.read().decode().strip()

        return f"{distro_name} {distro_version}", arch
    finally:
        ssh.close()

if __name__ == '__main__':
    target_ip = input("Enter the IP address of the remote server: ")
    username = input("Enter the SSH username for the remote server: ")
    password = input("Enter the SSH password for the remote server: ")

    os_name, os_accuracy = detect_remote_os(target_ip)

    if os_name is not None:
        is_linux = is_linux_os(os_name)
        if is_linux:
            print(f"The remote server is running Linux (Accuracy: {os_accuracy}%)")
            distro_version, arch = get_remote_system_info(target_ip, username, password)
            print(f"Remote system distribution and version: {distro_version}")
            print(f"Remote system architecture: {arch}")
        else:
            print(f"The remote server is NOT running Linux. Detected Operating System: {os_name} (Accuracy: {os_accuracy}%)")
    else:
        print("Failed to detect the operating system of the remote server.")

注意事项

  1. 远程命令执行:确保您有足够的权限在远程服务器上执行cat /etc/os-releaseuname -m命令。如果远程服务器设置了严格的权限控制,可能需要使用具有相应权限的用户账户进行连接。

  2. 错误处理:虽然/etc/os-release文件在大多数现代Linux发行版中是标准的,但仍有少数发行版可能使用不同的文件格式或位置存储系统信息。在实际使用中,您可能需要添加更完善的错误捕获和处理机制,以应对文件不存在、无法读取或其他异常情况。

实现效果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三希

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值