1. 程式人生 > >linux下獲取CPUID,MAC地址,硬碟序列號,主機板序列號

linux下獲取CPUID,MAC地址,硬碟序列號,主機板序列號

獲取CPUID:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <arpa/inet.h>
#include <string>
#include <fstream>

static bool get_cpu_id_by_asm(std::string & cpu_id)
{
    cpu_id.clear();

    unsigned int s1 = 0;
    unsigned int s2 = 0;
    asm volatile
    (
        "movl $0x01, %%eax; \n\t"
        "xorl %%edx, %%edx; \n\t"
        "cpuid; \n\t"
        "movl %%edx, %0; \n\t"
        "movl %%eax, %1; \n\t"
        : "=m"(s1), "=m"(s2)
    );

    if (0 == s1 && 0 == s2)
    {
        return(false);
    }

    char cpu[32] = { 0 };
    snprintf(cpu, sizeof(cpu), "%08X%08X", htonl(s2), htonl(s1));
    std::string(cpu).swap(cpu_id);

    return(true);
}

static void parse_cpu_id(const char * file_name, const char * match_words, std::string & cpu_id)
{
    cpu_id.c_str();

    std::ifstream ifs(file_name, std::ios::binary);
    if (!ifs.is_open())
    {
        return;
    }

    char line[4096] = { 0 };
    while (!ifs.eof())
    {
        ifs.getline(line, sizeof(line));
        if (!ifs.good())
        {
            break;
        }

        const char * cpu = strstr(line, match_words);
        if (NULL == cpu)
        {
            continue;
        }
        cpu += strlen(match_words);

        while ('\0' != cpu[0])
        {
            if (' ' != cpu[0])
            {
                cpu_id.push_back(cpu[0]);
            }
            ++cpu;
        }

        if (!cpu_id.empty())
        {
            break;
        }
    }

    ifs.close();
}

static bool get_cpu_id_by_system(std::string & cpu_id)
{
    cpu_id.c_str();

    const char * dmidecode_result = ".dmidecode_result.txt";
    char command[512] = { 0 };
    snprintf(command, sizeof(command), "dmidecode -t 4 | grep ID > %s", dmidecode_result);

    if (0 == system(command))
    {
        parse_cpu_id(dmidecode_result, "ID:", cpu_id);
    }

    unlink(dmidecode_result);

    return(!cpu_id.empty());
}

static bool get_cpu_id(std::string & cpu_id)
{
    if (get_cpu_id_by_asm(cpu_id))
    {
        return(true);
    }
    if (0 == getuid())
    {
        if (get_cpu_id_by_system(cpu_id))
        {
            return(true);
        }
    }
    return(false);
}

static void test_1()
{
    std::string cpu_id;
    if (get_cpu_id(cpu_id))
    {
        printf("cpu_id: [%s]\n", cpu_id.c_str());
    }
    else
    {
        printf("can not get cpu id\n");
    }
}

static void test_2()
{
    {
        std::string cpu_id;
        if (get_cpu_id_by_asm(cpu_id))
        {
            printf("cpu_id_by_asm: [%s]\n", cpu_id.c_str());
        }
        else
        {
            printf("can not get cpu id\n");
        }
    }
    {
        std::string cpu_id;
        if (get_cpu_id_by_system(cpu_id))
        {
            printf("cpu_id_by_sys: [%s]\n", cpu_id.c_str());
        }
        else
        {
            printf("can not get cpu id\n");
        }
    }
}

int main(int argc, char* argv[])
{
    test_1();
    test_2();
    return(0);
}

獲取MAC地址:(可以考慮加入ifconfig -a的解析,因為lshw實在太慢了)

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <fstream>

bool get_mac_address_by_ioctl(std::string & mac_address)
{
    mac_address.clear();

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        return(false);
    }

    struct ifreq ifr = { 0 };
    strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name) - 1);
    bool ret = (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0);

    close(sock);

    const char hex[] = 
    {
        '0', '1', '2', '3', '4', '5', '6', '7', 
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 
    };
    char mac[16] = { 0 };
    for (int index = 0; index < 6; ++index)
    {
         size_t value = ifr.ifr_hwaddr.sa_data[index] & 0xFF;
         mac[2 * index + 0] = hex[value / 16];
         mac[2 * index + 1] = hex[value % 16];
    }
    std::string(mac).swap(mac_address);

    return(ret);
}

static void parse_mac_address(const char * file_name, const char * match_words, std::string & mac_address)
{
    mac_address.c_str();

    std::ifstream ifs(file_name, std::ios::binary);
    if (!ifs.is_open())
    {
        return;
    }

    char line[4096] = { 0 };
    while (!ifs.eof())
    {
        ifs.getline(line, sizeof(line));
        if (!ifs.good())
        {
            break;
        }

        const char * mac = strstr(line, match_words);
        if (NULL == mac)
        {
            continue;
        }
        mac += strlen(match_words);

        while ('\0' != mac[0])
        {
            if (' ' != mac[0] && ':' != mac[0])
            {
                mac_address.push_back(mac[0]);
            }
            ++mac;
        }

        if (!mac_address.empty())
        {
            break;
        }
    }

    ifs.close();
}

static bool get_mac_address_by_system(std::string & mac_address)
{
    mac_address.c_str();

    const char * lshw_result = ".lshw_result.txt";
    char command[512] = { 0 };
    snprintf(command, sizeof(command), "lshw -c network | grep serial | head -n 1 > %s", lshw_result);

    if (0 == system(command))
    {
        parse_mac_address(lshw_result, "serial:", mac_address);
    }

    unlink(lshw_result);

    return(!mac_address.empty());
}

static bool get_mac_address(std::string & mac_address)
{
    if (get_mac_address_by_ioctl(mac_address))
    {
        return(true);
    }
    if (get_mac_address_by_system(mac_address))
    {
        return(true);
    }
    return(false);
}

static void test_1()
{
    std::string mac_address;
    if (get_mac_address(mac_address))
    {
        printf("mac_address: [%s]\n", mac_address.c_str());
    }
    else
    {
        printf("can not get mac address\n");
    }
}

static void test_2()
{
    {
        std::string mac_address;
        if (get_mac_address_by_ioctl(mac_address))
        {
            printf("mac_address: [%s]\n", mac_address.c_str());
        }
        else
        {
            printf("can not get mac address\n");
        }
    }
    {
        std::string mac_address;
        if (get_mac_address_by_system(mac_address))
        {
            printf("mac_address: [%s]\n", mac_address.c_str());
        }
        else
        {
            printf("can not get mac address\n");
        }
    }
}

int main(int argc, char * argv[])
{
    test_1();
    test_2();
    return(0);
}

獲取硬碟序列號:

#include <cctype>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include <scsi/sg.h>
#include <sys/ioctl.h>
#include <linux/hdreg.h>
#include <string>
#include <fstream>

static bool get_disk_name(std::string & disk_name)
{
    disk_name.c_str();

    std::ifstream ifs("/etc/mtab", std::ios::binary);
    if (!ifs.is_open())
    {
        return(false);
    }

    char line[4096] = { 0 };
    while (!ifs.eof())
    {
        ifs.getline(line, sizeof(line));
        if (!ifs.good())
        {
            break;
        }

        const char * disk = line;
        while (isspace(disk[0]))
        {
            ++disk;
        }

        const char * space = strchr(disk, ' ');
        if (NULL == space)
        {
            continue;
        }

        const char * mount = space + 1;
        while (isspace(mount[0]))
        {
            ++mount;
        }
        if ('/' != mount[0] || ' ' != mount[1])
        {
            continue;
        }

        while (space > disk && isdigit(space[-1]))
        {
            --space;
        }

        if (space > disk)
        {
            std::string(disk, space).swap(disk_name);
            break;
        }
    }

    ifs.close();

    return(!disk_name.empty());
}

static void trim_serial(const void * serial, size_t serial_len, std::string & serial_no)
{
    const char * serial_s = static_cast<const char *>(serial);
    const char * serial_e = serial_s + serial_len;
    while (serial_s < serial_e)
    {
        if (isspace(serial_s[0]))
        {
            ++serial_s;
        }
        else if ('\0' == serial_e[-1] || isspace(serial_e[-1]))
        {
            --serial_e;
        }
        else
        {
            break;
        }
    }

    if (serial_s < serial_e)
    {
        std::string(serial_s, serial_e).swap(serial_no);
    }
}

static bool get_disk_serial_by_way_1(const std::string & disk_name, std::string & serial_no)
{
    serial_no.clear();

    int fd = open(disk_name.c_str(), O_RDONLY);
    if (-1 == fd)
    {
        return(false);
    }

    struct hd_driveid drive = { 0 };
    if (0 == ioctl(fd, HDIO_GET_IDENTITY, &drive))
    {
        trim_serial(drive.serial_no, sizeof(drive.serial_no), serial_no);
    }

    close(fd);

    return(!serial_no.empty());
}

static bool scsi_io(
                int fd, unsigned char * cdb, 
                unsigned char cdb_size, int xfer_dir, 
                unsigned char * data, unsigned int data_size, 
                unsigned char * sense, unsigned int sense_len
            )
{
    sg_io_hdr_t io_hdr = { 0 };
    io_hdr.interface_id = 'S';
    io_hdr.cmdp = cdb;
    io_hdr.cmd_len = cdb_size;
    io_hdr.sbp = sense;
    io_hdr.mx_sb_len = sense_len;
    io_hdr.dxfer_direction = xfer_dir;
    io_hdr.dxferp = data;
    io_hdr.dxfer_len = data_size;
    io_hdr.timeout = 5000;

    if (ioctl(fd, SG_IO, &io_hdr) < 0)
    {
        return(false);
    }

    if (SG_INFO_OK != (io_hdr.info & SG_INFO_OK_MASK) && io_hdr.sb_len_wr > 0)
    {
        return(false);
    }

    if (io_hdr.masked_status || io_hdr.host_status || io_hdr.driver_status)
    {
        return(false);
    }

    return(true);
}

static bool get_disk_serial_by_way_2(const std::string & disk_name, std::string & serial_no)
{
    serial_no.clear();

    int fd = open(disk_name.c_str(), O_RDONLY);
    if (-1 == fd)
    {
        return(false);
    }

    int version = 0;
    if (ioctl(fd, SG_GET_VERSION_NUM, &version) < 0 || version < 30000)
    {
        close(fd);
        return(false);
    }

    const unsigned int data_size = 0x00ff;
    unsigned char data[data_size] = { 0 };
    const unsigned int sense_len = 32;
    unsigned char sense[sense_len] = { 0 };
    unsigned char cdb[] = { 0x12, 0x01, 0x80, 0x00, 0x00, 0x00 };
    cdb[3] = (data_size >> 8) & 0xff;
    cdb[4] = (data_size & 0xff);

    if (scsi_io(fd, cdb, sizeof(cdb), SG_DXFER_FROM_DEV, data, data_size, sense, sense_len))
    {
        int page_len = data[3];
        trim_serial(data + 4, page_len, serial_no);
    }

    close(fd);

    return(!serial_no.empty());
}

static bool parse_serial(const char * line, int line_size, const char * match_words, std::string & serial_no)
{
    const char * serial_s = strstr(line, match_words);
    if (NULL == serial_s)
    {
        return(false);
    }
    serial_s += strlen(match_words);
    while (isspace(serial_s[0]))
    {
        ++serial_s;
    }

    const char * serial_e = line + line_size;
    const char * comma = strchr(serial_s, ',');
    if (NULL != comma)
    {
        serial_e = comma;
    }

    while (serial_e > serial_s && isspace(serial_e[-1]))
    {
        --serial_e;
    }

    if (serial_e <= serial_s)
    {
        return(false);
    }

    std::string(serial_s, serial_e).swap(serial_no);

    return(true);
}

static void get_serial(const char * file_name, const char * match_words, std::string & serial_no)
{
    serial_no.c_str();

    std::ifstream ifs(file_name, std::ios::binary);
    if (!ifs.is_open())
    {
        return;
    }

    char line[4096] = { 0 };
    while (!ifs.eof())
    {
        ifs.getline(line, sizeof(line));
        if (!ifs.good())
        {
            break;
        }

        if (0 == ifs.gcount())
        {
            continue;
        }

        if (parse_serial(line, ifs.gcount() - 1, match_words, serial_no))
        {
            break;
        }
    }

    ifs.close();
}

static bool get_disk_serial_by_way_3(const std::string & disk_name, std::string & serial_no)
{
    serial_no.c_str();

    const char * hdparm_result = ".hdparm_result.txt";
    char command[512] = { 0 };
    snprintf(command, sizeof(command), "hdparm -i %s | grep SerialNo > %s", disk_name.c_str(), hdparm_result);

    if (0 == system(command))
    {
        get_serial(hdparm_result, "SerialNo=", serial_no);
    }

    unlink(hdparm_result);

    return(!serial_no.empty());
}

static bool get_disk_serial_by_way_4(std::string & serial_no)
{
    serial_no.c_str();

    const char * lshw_result = ".lshw_result.txt";
    char command[512] = { 0 };
    snprintf(command, sizeof(command), "lshw -class disk | grep serial > %s", lshw_result);

    if (0 == system(command))
    {
        get_serial(lshw_result, "serial:", serial_no);
    }

    unlink(lshw_result);

    return(!serial_no.empty());
}

static bool get_disk_serial_number(std::string & serial_no)
{
    if (0 != getuid())
    {
        return(false);
    }

    std::string disk_name;
    if (get_disk_name(disk_name))
    {
        if (get_disk_serial_by_way_1(disk_name, serial_no))
        {
            return(true);
        }
        if (get_disk_serial_by_way_2(disk_name, serial_no))
        {
            return(true);
        }
        if (get_disk_serial_by_way_3(disk_name, serial_no))
        {
            return(true);
        }
    }
    if (get_disk_serial_by_way_4(serial_no))
    {
        return(true);
    }
    return(false);
}

static void test_1()
{
    std::string serial_no;
    if (get_disk_serial_number(serial_no))
    {
        printf("serial_number: [%s]\n", serial_no.c_str());
    }
    else
    {
        printf("get serial number failed\n");
    }
}

static void test_2()
{
    std::string disk_name;
    if (get_disk_name(disk_name))
    {
        printf("disk_name:[%s]\n", disk_name.c_str());
        {
            std::string serial_no;
            get_disk_serial_by_way_1(disk_name, serial_no);
            printf("get_serial_by_way_1:[%s]\n", serial_no.c_str());
        }
        {
            std::string serial_no;
            get_disk_serial_by_way_2(disk_name, serial_no);
            printf("get_serial_by_way_2:[%s]\n", serial_no.c_str());
        }
        {
            std::string serial_no;
            get_disk_serial_by_way_3(disk_name, serial_no);
            printf("get_serial_by_way_3:[%s]\n", serial_no.c_str());
        }
    }
    {
        std::string serial_no;
        get_disk_serial_by_way_4(serial_no);
        printf("get_serial_by_way_4:[%s]\n", serial_no.c_str());
    }
}

int main(int argc, char * argv[])
{
    printf("---------------\n");
    test_1();
    printf("---------------\n");
    test_2();
    printf("---------------\n");
    return(0);
}

獲取主機板序列號:(沒有找到純程式碼的實現方法)

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <fstream>

static void parse_board_serial(const char * file_name, const char * match_words, std::string & board_serial)
{
    board_serial.c_str();

    std::ifstream ifs(file_name, std::ios::binary);
    if (!ifs.is_open())
    {
        return;
    }

    char line[4096] = { 0 };
    while (!ifs.eof())
    {
        ifs.getline(line, sizeof(line));
        if (!ifs.good())
        {
            break;
        }

        const char * board = strstr(line, match_words);
        if (NULL == board)
        {
            continue;
        }
        board += strlen(match_words);

        while ('\0' != board[0])
        {
            if (' ' != board[0])
            {
                board_serial.push_back(board[0]);
            }
            ++board;
        }

        if ("None" == board_serial)
        {
            board_serial.clear();
            continue;
        }

        if (!board_serial.empty())
        {
            break;
        }
    }

    ifs.close();
}

static bool get_board_serial_by_system(std::string & board_serial)
{
    board_serial.c_str();

    const char * dmidecode_result = ".dmidecode_result.txt";
    char command[512] = { 0 };
    snprintf(command, sizeof(command), "dmidecode -t 2 | grep Serial > %s", dmidecode_result);

    if (0 == system(command))
    {
        parse_board_serial(dmidecode_result, "Serial Number:", board_serial);
    }

    unlink(dmidecode_result);

    return(!board_serial.empty());
}

static bool get_board_serial_number(std::string & board_serial)
{
    if (0 == getuid())
    {
        if (get_board_serial_by_system(board_serial))
        {
            return(true);
        }
    }
    return(false);
}

static void test()
{
    std::string board_serial;
    if (get_board_serial_number(board_serial))
    {
        printf("board_serial: [%s]\n", board_serial.c_str());
    }
    else
    {
        printf("can not get board id\n");
    }
}

int main(int argc, char* argv[])
{
    test();
    return(0);
}

方便測試的Makefile:

build :
	g++ -o get_cpu_id get_cpu_id.cpp
	g++ -o get_mac_address get_mac_address.cpp
	g++ -o get_disk_serial_number get_disk_serial_number.cpp
	g++ -o get_board_serial_number get_board_serial_number.cpp

run   :
	@echo "--------------------"
	@- ./get_cpu_id
	@echo "--------------------"
	@- ./get_mac_address
	@echo "--------------------"
	@- ./get_disk_serial_number
	@echo "--------------------"
	@- ./get_board_serial_number
	@echo "--------------------"

clean : 
	-rm get_cpu_id
	-rm get_mac_address
	-rm get_disk_serial_number
	-rm get_board_serial_number

rebuild : clean build

編譯:make 或者 make build

執行:make run 或者 sudo make run (上面大多數資訊都需要超級使用者許可權才能獲取到結果)

清理:make clean (這個寫得太死了,本來是想刪除非cpp檔案的,shell寫不出來)

重編:make rebuild

參考網站:http://www.xuebuyuan.com/1789815.html

相關推薦

linux獲取CPUIDMAC地址硬碟序列主機板序列

獲取CPUID: #include <cstdio> #include <cstring> #include <cstdlib> #include <arpa/inet.h> #include <string> #

java工具類,在Windows,Linux系統獲取電腦的MAC地址、本地IP、電腦名

copy iter 去掉m [] equals linu stat cli catch package com.cloudssaas.util; import java.io.BufferedReader; import java.io.IOException;

linux獲取本機IPv6地址、字首、閘道器

獲取本機IPv6資訊命令:cat /proc/net/if_inet6 [email protected]:/home/user1/# cat /proc/net/if_inet6 fe80000000000000922b34fffe4e70f4 02 40 20 80 et

Linux獲取IP、MAC、掩碼的shell指令碼

Mask:ifconfig |grep inet| sed -n '1p'|awk '{print $4}'|awk -F ':' '{print $2}'IP:ifconfig |grep inet| sed -n '1p'|awk '{print $2}'|awk

centos 7 獲取CPUIDMAC地址主機板序列

獲取CPUID: #include <cstdio> #include <cstring> #include <cstdlib> #include <arpa/inet.h> #include

LINUX獲取網絡卡IP地址MAC地址子網掩碼程式參考

/* mode time:20120727 LINUX下獲取IP地址和MAC地址.程式相關結構體在程式後面。 列印網絡卡的ip地址 子網掩碼 廣播地址 mac地址 環境: [[email protected] temp]# uname -a Linux b

linux如何用正則表達式執行ifconfig命令只提取IP地址

linux 如何 正則 方法太多,先簡單到簡捷循序漸進。1、 [root@centos6 ~]# ifconfig eth0|grep ‘inet addr:‘ ###過濾不是IP地址的行 inet addr:192.168.16.100 Bcast:192.168.16.255

C/C++:Windows程式設計—程式碼獲取本地所有網絡卡資訊(網絡卡描述IP地址子網掩碼MAC地址

先看效果 看程式碼 使用 GetAdaptersInfo 函式獲取網絡卡的所有資訊。 MSDN函式說明 https://docs.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getadapters

iOS 獲取裝置資訊mac地址IP地址裝置名稱

#import "DeviceInfoUtil.h" #import "GlobleData.h" #import "sys/utsname.h" #import <AdSupport/AdSupport.h> #import <ifaddrs.h>

C# 獲取Windows系統:Cpu使用率記憶體使用率Mac地址磁碟使用率

一、獲取CPU使用率: #region 獲取CPU使用率         #region AIP宣告          [DllImport("IpHlpApi.dll")]     &n

android 獲取手機上面的IMSI序列IMEIMAC地址IP地址當前時間當前經緯度獲取網路型別

// 獲取IMSI public void getIMSI(Context context) { TelephonyManager telManager = (TelephonyManager) context

C/C++: linux獲取程序ID父程序ID

#include <iostream> #include <sys/types.h> #include <unistd.h> #include <stdio.

android UDID獲取:android 裝置SN的獲取 續 android 裝置唯一碼的獲取CpuMac地址

http://blog.csdn.net/hpccn/article/details/7872141 這個方法使用中發現一些不完美的地方. -------------------------------------- 新的方法: 在使用命令列, adb device  a

linux使用ioctl() 獲取本機mac地址、ip地址等等

       在linux下,我們知道可以通過ifconfig獲取mac地址和ip地址等相關資訊,但是如果要使用gcc程式實現的話,我們就需要使用到系統所提供的一個函式ioctl(),iotec函式是對裝置的i/o通道進行管理的函式。由於這個函式用途比較多,如果要學習可以參

Python獲取本機MAC地址ip和主機名

獲取mac地址: import uuid def get_mac_address(): mac=uuid.UUID(int = uuid.getnode()).hex[-12:] re

獲取請求主機IP地址,如果通過代理進來則透過防火墻獲取真實IP地址

cas return ++ strip dex except servlet desc 請求 /** * 獲取請求主機IP地址,如果通過代理進來,則透過防火墻獲取真實IP地址; * @Title: getIpAddress * @Descr

Linux實現客戶端兩連跳ping百度修改dns和nmcil的用法

1.客戶端跳兩次路由器ping百度 rht vmctl reset 重置虛擬機器 真機和虛擬機器開啟火牆策略 用在配置網路單元學的修改兩機閘道器 設定server為雙網絡卡路由端接觸客戶端Desktop閘道器為1.1.1.100 路由器端設定GATEWAY為真機,記得syste

linux 設置 MySQL8 表名大小寫不敏感方法解決設置後無法啟動 MySQL 服務的問題

服務 修改 比較 數據庫 res 重啟 啟動 mys system 在安裝完成之後,初始化數據庫之前,修改 my.cnf 打開mysql配置文件 vim /etc/my.cnf 在尾部追加一行 lower_case_table_names=1 並保存,然後再初始化數據庫。

linux在伺服器上配置scrapy框架的python爬蟲使用mysql資料庫儲存

最近在做把 爬蟲部署到伺服器上,爬下來的資料再存到資料庫裡。 因為伺服器是linux系統的,所以我們事先需要配置一些環境檔案以及依賴的庫 1、裝python 這一步沒啥好說的吧 2、裝pip,然後再用pip裝依賴的庫: pip install pymysql

Linux企業級的高階網路配置(bond&team橋接)

BOND&TEAM 讓Linux核心支援網絡卡繫結驅動。常見的網絡卡繫結驅動有三種模式——mode0、mode1、mode6。 mode0(平衡負載模式):平時兩塊網絡卡均工作,且自動備援,但需要在與伺服器本地網絡卡相連的交換機裝置上進行埠聚合來支援繫結技術。 mode1(平衡備