Search code examples
pythonbatch-fileserial-number

Getting computer serial number with python and .bat file


I have been studying for exams recently and the textbook I was reading told me that the command (in CMD) for getting a computers serial number is as follows - (as one method of lowering piracy).

wmic bios get serialnumber

I decided to try this for myself using python, where I wanted to get the serial number of my own computer, I created a batch file (.bat) and recorded the serial number to a txt file which I thought I could then read off in python, this created more questions if anything... here is the code I currently have:

SerialNumber.bat (new to bat files by the way)

SET num=wmic bios get serialnumber

%num% > serial.txt

What serial.txt looks like (modified slightly to not give away my serial number)

enter image description here

Readtxt.py

# Trying to read in two different ways
with open("serial.txt", "r") as file:
    print(file.read())

lines = []
for line in open("serial.txt"):
    lines.append(line)
print(lines)

which outputs: (not showing full image again)

enter image description here

the questions are:

  1. How would I store the serial number as some string?
  2. Why does each different method I use to read provide different outputs?

Thanks for any answers :)


Solution

  • When redirecting to a file wmic writes UTF-16-LE with a BOM

    > wmic bios get serialnumber >serial.txt
    
    > hex.exe serial.txt
    HEX:       +00 01 02 03 04 05 06 07  08 09 0a 0b 0c 0d 0e 0f  0123456789abcdef
    0000000000: FF FE 53 00 65 00 72 00  69 00 61 00 6C 00 4E 00  .■S.e.r.i.a.l.N.
    0000000010: 75 00 6D 00 62 00 65 00  72 00 20 00 20 00 0D 00  u.m.b.e.r. . ...
    
    > type readtext.py
    with open("serial.txt", 'rb') as file:
        print(file.read().decode('utf-16'))
    
    > py readtext.py
    SerialNumber
    5xxxxyyyy