How can I get the serial number of a hard disk drive using Python on Linux?

I would like to use a Python module to do that instead of running an external program such as hdparm. Perhaps using the fcntl module?

解决方案

Linux

As you suggested, fcntl is the way to do this on Linux. The C code you want to translate looks like this:

static struct hd_driveid hd;

int fd;

if ((fd = open("/dev/hda", O_RDONLY | O_NONBLOCK)) < 0) {

printf("ERROR opening /dev/hda\n");

exit(1);

}

if (!ioctl(fd, HDIO_GET_IDENTITY, &hd)) {

printf("%.20s\n", hd.serial_no);

} else if (errno == -ENOMSG) {

printf("No serial number available\n");

} else {

perror("ERROR: HDIO_GET_IDENTITY");

exit(1);

}

Translated into Python on Ubuntu 9.10, it goes a little something like this:

import sys, os, fcntl, struct

if os.geteuid() > 0:

print("ERROR: Must be root to use")

sys.exit(1)

with open(sys.argv[1], "rb") as fd:

# tediously derived from the monster struct defined in

# see comment at end of file to verify

hd_driveid_format_str = "@ 10H 20s 3H 8s 40s 2B H 2B H 4B 6H 2B I 36H I Q 152H"

# Also from

HDIO_GET_IDENTITY = 0x030d

# How big a buffer do we need?

sizeof_hd_driveid = struct.calcsize(hd_driveid_format_str)

# ensure our format string is the correct size

# 512 is extracted using sizeof(struct hd_id) in the c code

assert sizeof_hd_driveid == 512

# Call native function

buf = fcntl.ioctl(fd, HDIO_GET_IDENTITY, " " * sizeof_hd_driveid)

fields = struct.unpack(hd_driveid_format_str, buf)

serial_no = fields[10].strip()

model = fields[15].strip()

print("Hard Disk Model: %s" % model)

print(" Serial Number: %s" % serial_no)

## For documentation purposes, this is the struct copied from

# struct hd_driveid {

# unsigned short config; /* lots of obsolete bit flags */

# unsigned short cyls; /* Obsolete, "physical" cyls */

# unsigned short reserved2; /* reserved (word 2) */

# unsigned short heads; /* Obsolete, "physical" heads */

# unsigned short track_bytes; /* unformatted bytes per track */

# unsigned short sector_bytes; /* unformatted bytes per sector */

# unsigned short sectors; /* Obsolete, "physical" sectors per track */

# unsigned short vendor0; /* vendor unique */

# unsigned short vendor1; /* vendor unique */

# unsigned short vendor2; /* Retired vendor unique */

# unsigned char serial_no[20]; /* 0 = not_specified */

# unsigned short buf_type; /* Retired */

# unsigned short buf_size; /* Retired, 512 byte increments

# * 0 = not_specified

# */

# unsigned short ecc_bytes; /* for r/w long cmds; 0 = not_specified */

# unsigned char fw_rev[8]; /* 0 = not_specified */

# unsigned char model[40]; /* 0 = not_specified */

# unsigned char max_multsect; /* 0=not_implemented */

# unsigned char vendor3; /* vendor unique */

# unsigned short dword_io; /* 0=not_implemented; 1=implemented */

# unsigned char vendor4; /* vendor unique */

# unsigned char capability; /* (upper byte of word 49)

# * 3: IORDYsup

# * 2: IORDYsw

# * 1: LBA

# * 0: DMA

# */

# unsigned short reserved50; /* reserved (word 50) */

# unsigned char vendor5; /* Obsolete, vendor unique */

# unsigned char tPIO; /* Obsolete, 0=slow, 1=medium, 2=fast */

# unsigned char vendor6; /* Obsolete, vendor unique */

# unsigned char tDMA; /* Obsolete, 0=slow, 1=medium, 2=fast */

# unsigned short field_valid; /* (word 53)

# * 2: ultra_ok word 88

# * 1: eide_ok words 64-70

# * 0: cur_ok words 54-58

# */

# unsigned short cur_cyls; /* Obsolete, logical cylinders */

# unsigned short cur_heads; /* Obsolete, l heads */

# unsigned short cur_sectors; /* Obsolete, l sectors per track */

# unsigned short cur_capacity0; /* Obsolete, l total sectors on drive */

# unsigned short cur_capacity1; /* Obsolete, (2 words, misaligned int) */

# unsigned char multsect; /* current multiple sector count */

# unsigned char multsect_valid; /* when (bit0==1) multsect is ok */

# unsigned int lba_capacity; /* Obsolete, total number of sectors */

# unsigned short dma_1word; /* Obsolete, single-word dma info */

# unsigned short dma_mword; /* multiple-word dma info */

# unsigned short eide_pio_modes; /* bits 0:mode3 1:mode4 */

# unsigned short eide_dma_min; /* min mword dma cycle time (ns) */

# unsigned short eide_dma_time; /* recommended mword dma cycle time (ns) */

# unsigned short eide_pio; /* min cycle time (ns), no IORDY */

# unsigned short eide_pio_iordy; /* min cycle time (ns), with IORDY */

# unsigned short words69_70[2]; /* reserved words 69-70

# * future command overlap and queuing

# */

# unsigned short words71_74[4]; /* reserved words 71-74

# * for IDENTIFY PACKET DEVICE command

# */

# unsigned short queue_depth; /* (word 75)

# * 15:5 reserved

# * 4:0 Maximum queue depth -1

# */

# unsigned short words76_79[4]; /* reserved words 76-79 */

# unsigned short major_rev_num; /* (word 80) */

# unsigned short minor_rev_num; /* (word 81) */

# unsigned short command_set_1; /* (word 82) supported

# * 15: Obsolete

# * 14: NOP command

# * 13: READ_BUFFER

# * 12: WRITE_BUFFER

# * 11: Obsolete

# * 10: Host Protected Area

# * 9: DEVICE Reset

# * 8: SERVICE Interrupt

# * 7: Release Interrupt

# * 6: look-ahead

# * 5: write cache

# * 4: PACKET Command

# * 3: Power Management Feature Set

# * 2: Removable Feature Set

# * 1: Security Feature Set

# * 0: SMART Feature Set

# */

# unsigned short command_set_2; /* (word 83)

# * 15: Shall be ZERO

# * 14: Shall be ONE

# * 13: FLUSH CACHE EXT

# * 12: FLUSH CACHE

# * 11: Device Configuration Overlay

# * 10: 48-bit Address Feature Set

# * 9: Automatic Acoustic Management

# * 8: SET MAX security

# * 7: reserved 1407DT PARTIES

# * 6: SetF sub-command Power-Up

# * 5: Power-Up in Standby Feature Set

# * 4: Removable Media Notification

# * 3: APM Feature Set

# * 2: CFA Feature Set

# * 1: READ/WRITE DMA QUEUED

# * 0: Download MicroCode

# */

# unsigned short cfsse; /* (word 84)

# * cmd set-feature supported extensions

# * 15: Shall be ZERO

# * 14: Shall be ONE

# * 13:6 reserved

# * 5: General Purpose Logging

# * 4: Streaming Feature Set

# * 3: Media Card Pass Through

# * 2: Media Serial Number Valid

# * 1: SMART selt-test supported

# * 0: SMART error logging

# */

# unsigned short cfs_enable_1; /* (word 85)

# * command set-feature enabled

# * 15: Obsolete

# * 14: NOP command

# * 13: READ_BUFFER

# * 12: WRITE_BUFFER

# * 11: Obsolete

# * 10: Host Protected Area

# * 9: DEVICE Reset

# * 8: SERVICE Interrupt

# * 7: Release Interrupt

# * 6: look-ahead

# * 5: write cache

# * 4: PACKET Command

# * 3: Power Management Feature Set

# * 2: Removable Feature Set

# * 1: Security Feature Set

# * 0: SMART Feature Set

# */

# unsigned short cfs_enable_2; /* (word 86)

# * command set-feature enabled

# * 15: Shall be ZERO

# * 14: Shall be ONE

# * 13: FLUSH CACHE EXT

# * 12: FLUSH CACHE

# * 11: Device Configuration Overlay

# * 10: 48-bit Address Feature Set

# * 9: Automatic Acoustic Management

# * 8: SET MAX security

# * 7: reserved 1407DT PARTIES

# * 6: SetF sub-command Power-Up

# * 5: Power-Up in Standby Feature Set

# * 4: Removable Media Notification

# * 3: APM Feature Set

# * 2: CFA Feature Set

# * 1: READ/WRITE DMA QUEUED

# * 0: Download MicroCode

# */

# unsigned short csf_default; /* (word 87)

# * command set-feature default

# * 15: Shall be ZERO

# * 14: Shall be ONE

# * 13:6 reserved

# * 5: General Purpose Logging enabled

# * 4: Valid CONFIGURE STREAM executed

# * 3: Media Card Pass Through enabled

# * 2: Media Serial Number Valid

# * 1: SMART selt-test supported

# * 0: SMART error logging

# */

# unsigned short dma_ultra; /* (word 88) */

# unsigned short trseuc; /* time required for security erase */

# unsigned short trsEuc; /* time required for enhanced erase */

# unsigned short CurAPMvalues; /* current APM values */

# unsigned short mprc; /* master password revision code */

# unsigned short hw_config; /* hardware config (word 93)

# * 15: Shall be ZERO

# * 14: Shall be ONE

# * 13:

# * 12:

# * 11:

# * 10:

# * 9:

# * 8:

# * 7:

# * 6:

# * 5:

# * 4:

# * 3:

# * 2:

# * 1:

# * 0: Shall be ONE

# */

# unsigned short acoustic; /* (word 94)

# * 15:8 Vendor's recommended value

# * 7:0 current value

# */

# unsigned short msrqs; /* min stream request size */

# unsigned short sxfert; /* stream transfer time */

# unsigned short sal; /* stream access latency */

# unsigned int spg; /* stream performance granularity */

# unsigned long long lba_capacity_2;/* 48-bit total number of sectors */

# unsigned short words104_125[22];/* reserved words 104-125 */

# unsigned short last_lun; /* (word 126) */

# unsigned short word127; /* (word 127) Feature Set

# * Removable Media Notification

# * 15:2 reserved

# * 1:0 00 = not supported

# * 01 = supported

# * 10 = reserved

# * 11 = reserved

# */

# unsigned short dlf; /* (word 128)

# * device lock function

# * 15:9 reserved

# * 8 security level 1:max 0:high

# * 7:6 reserved

# * 5 enhanced erase

# * 4 expire

# * 3 frozen

# * 2 locked

# * 1 en/disabled

# * 0 capability

# */

# unsigned short csfo; /* (word 129)

# * current set features options

# * 15:4 reserved

# * 3: auto reassign

# * 2: reverting

# * 1: read-look-ahead

# * 0: write cache

# */

# unsigned short words130_155[26];/* reserved vendor words 130-155 */

# unsigned short word156; /* reserved vendor word 156 */

# unsigned short words157_159[3];/* reserved vendor words 157-159 */

# unsigned short cfa_power; /* (word 160) CFA Power Mode

# * 15 word 160 supported

# * 14 reserved

# * 13

# * 12

# * 11:0

# */

# unsigned short words161_175[15];/* Reserved for CFA */

# unsigned short words176_205[30];/* Current Media Serial Number */

# unsigned short words206_254[49];/* reserved words 206-254 */

# unsigned short integrity_word; /* (word 255)

# * 15:8 Checksum

# * 7:0 Signature

# */

# };

Apologies for the length, I thought it useful to include the original C struct as a comment. Also, I'm pretty new to both the fcntl and struct modules, so I may be doing something unidomatic. In anycase, run from the command-line (with root privelidges) it looks like this (I've redacted my exact serial for privacy):

fmark@fmark-laptop:~/Desktop/hdserial$ sudo python hd.py "/dev/sda"

Hard Disk Model: FUJITSU MHV2080BH PL

Serial Number: NW--------

What's going on here?

In order to be able to understand what is going on here, you need to look at the #include in the original C program. This include imports the HDIO_GET_IDENTITY constant and the struct hd_driveid. I've copied the struct as a comment into the python sourcecode above, so I won't repeat it here. To find out what is going on with HDIO_GET_IDENTITY, grep the source-code for it (on Ubuntu this is at /usr/include/linux/hdreg.h. You should find something like this:

#define HDIO_GET_IDENTITY 0x030d /* get IDE identification info */

Thus, you find that HDIO_GET_IDENTITY is just a constant that tells fcntl that you are interested in getting HD info. As you will notice, that same value (0x030d is an integer in hexadecimal notation) is assigned to a variable in the python code.

Windows

I realise now you are interested in Linux, but I'll keep this here for posterity. The following will get the HDD serial number on Windows (you will need to install the wmi package):

import wmi

c = wmi.WMI()

for item in c.Win32_PhysicalMedia():

print item

python 模拟硬盘id,如何使用Python获取硬盘序列号相关推荐

  1. Python模拟登录某橙色软件并获取所有订单,康康买了啥奇奇怪怪的东西?

    温馨提示 现在宝换成了滑块验证了, 比较难解决这个问题,以下的代码没法用了, 仅作学习参考研究之用吧. 本篇内容 python模拟登录宝网页 获取登录用户的所有订单详情 学会应对出现验证码的情况 体会 ...

  2. python模拟登陆友盟网站并获取我的站点信息

    新建config.py文件: 1.分析友盟网站登陆 predata={ "token":"7e63b6d788d9a9fa8478646a508bd44c", ...

  3. python 模拟浏览器selenium_浅谈python爬虫使用Selenium模拟浏览器行为

    前几天有位微信读者问我一个爬虫的问题,就是在爬去百度贴吧首页的热门动态下面的图片的时候,爬取的图片总是爬取不完整,比首页看到的少.原因他也大概分析了下,就是后面的图片是动态加载的.他的问题就是这部分动 ...

  4. python模拟登录网站_用python实现模拟登录人人网

    我决定从头说起.懂的人可以快速略过前面理论看最后几张图. web基础知识 从OSI参考模型(从低到高:物理层,数据链路层,网络层,传输层,会话层,表示层,应用层)来说,我们的互联网属于应用层.从TCP ...

  5. python模拟足球射门_用Python模拟2018世界杯夺冠之路

    2018俄罗斯世界杯小组抽签出炉,几家欢喜几家愁.世界杯从来就不乏看点,东道主俄罗斯能走多远.德国能否卫冕.西班牙是否有望东山再起.两位球王谁更接近大力神杯...距世界杯开幕还有半年时间,一切都是未知 ...

  6. python 模拟浏览器selenium_从零开始写Python爬虫 --- 3.1 Selenium模拟浏览器

    本来说好要写Mechanize模拟浏览器的,结果一看居然只支持2.x版本的Python,而且已经长久没有更新维护了,本着学新不学旧的原则,我决定跳过他,直接开学Selenium(其实就是我懒,逃 Se ...

  7. python模拟浏览器模块_在Python中使用mechanize模块模拟浏览器功能

    知道如何快速在命令行或者python脚本中实例化一个浏览器通常是非常有用的. 每次我需要做任何关于web的自动任务时,我都使用这段python代码去模拟一个浏览器. import mechanize ...

  8. python模拟一个简单的取款机,python简单区块链模拟详解

    最近学习了一点python,那就试着做一做简单的编程练习. 首先是这个编程的指导图,如下: 对的,类似一个简单区块链的模拟. 代码如下: class DaDaBlockCoin: #index 索引, ...

  9. Python模拟键盘输入(附Python 键位码表)

    在Python中我们要模拟键盘进行一些输入 安装第三方库win32api(如果没有就需要安装) 1.Win+R,输入cmd打开命令行 2.输入pip install pypiwin32 实质访问的下载 ...

最新文章

  1. html input type=quot;filequot;,科技常识:关于type=quot;filequot;的input框样式修改小结...
  2. linux的ll命令参数,linux ll命令参数的详解
  3. 剑指offer:矩形覆盖 python 实现
  4. sparkSQL1.1入门之二:sparkSQL执行架构
  5. Openstack组件部署 — keystone(domain, projects, users, and roles)
  6. [转]关于形如--error LNK2005: xxx 已经在 msvcrtd.lib ( MSVCR90D.dll ) 中定义--的问题分析解决...
  7. 函数传参之商品价格计算—JS学习笔记2015-6-6(第50天)
  8. Routing a Marathon Race
  9. html5触摸指定区域,HTML5/CSS3系列教程:HTML5 区域(Sectioning)的重要性
  10. 在Android中运用RxJava
  11. jQuery1.11源码分析(8)-----jQuery调用Sizzle引擎的相关API
  12. 最全Pycharm教程(6)——将Pycharm作为Vim编辑器使用
  13. 银联在线支付网关,实现快捷安全的全球支付
  14. 【全套完结】电磁场与电磁波实验-----全套Matlab仿真实验
  15. 关于CDN那些名词,你知道吗?
  16. lightoj 1009 - Back to Underworld 【DFS】
  17. 展会邀约 | 昂视与您相约BTF第12届上海锂电展
  18. [推荐]“痘痘”与所对应的疾病
  19. cocos creator开发微信小游戏(五)贪吃蛇大作战
  20. Ubuntu 设置时间同步

热门文章

  1. 刷新iframe页面 allowtransparency 属性
  2. 2022全年度吸尘器十大热门品牌销量榜单
  3. 【VMware vSAN 7.0】6.13 将双节点集群分配给共享见证主机—我们有软硬件解决方案
  4. Java动态数据生成PDF文档及下载
  5. 要尽量把外链发到权重高的网站
  6. 原生JavaScript 06-相册选择功能
  7. 2022医药数据采集-整合超过10万个数据信息源
  8. springboot整合Redis分布式锁最佳实践
  9. html如果更改背景音乐,如何替换视频背景音乐(替换视频中的音频),这个方法超简单!...
  10. 未来企业IT技术关注点及IT架构变革探讨