get unique machine id in python 2.7 - python

import pycpuid
b=pycpuid.cpuid(1)
pid=str(b[0]+b[3])
Is that the same every time system reboots?
Not sure what passing different ints does to cpuid function?
ie: no matter what OS or version of that OS is installed, or network adapters...
if python is run and this function used, it will always return same value
thats what im looking for, based on the CPU, no other hardware

The CPUID call will not be unique (but it won't change either - so it will be the same across OSes (it's an opcode implemented in the processor)) for a specific computer. Only a subset of processors (in the Pentium 3 range for Intel and a few other brands) returns an actual serial number. AMD does not return a serial number in any version.
The integer given to cpuid tells it what information it should retrieve - see the EAX column in the documentation for the opcode - i.e. if it should return a specific check for a feature. You shouldn't have to call it directly, but instead use the helper functions defined in pycpuid (which gives arguments according to what it should retrieve).
If you're calling cpuinfo with an argument of 1, you're asking it to return the information given when EAX is 1:
INPUT EAX = 1: Returns Model, Family, Stepping Information
When CPUID executes with EAX set to 1, version information is returned in EAX.
INPUT EAX = 1: Returns Additional Information in EBX
When CPUID executes with EAX set to 1, additional information is returned to the EBX register: - Brand index (low byte of EBX) - this number provides an entry into a brand string table that contains brand strings for IA-32 processors. More information about this field is provided later in this section.
CLFLUSH instruction cache line size (second byte of EBX)
this number indicates the size of the cache line flushed with CLFLUSH instruction in 8-byte increments. This field was introduced in the Pentium 4 processor.
Local APIC ID (high byte of EBX)
this number is the 8-bit ID that is assigned to the local APIC on the processor during power up. This field was introduced in the Pentium 4 processor.

Latest Linux versions come with auto-generated machine id which can be found at /etc/machine-id .
import os
machineId = os.popen("cat /etc/machine-id").read()
print(machineId)
Ubuntu Documentation for Machine Id
FreeDesktop Documentation for Machine Id

I would recommend using the following code and syntax instead of pycpuid. I hope this helps.
#The following can be used to generate a random id
import uuid
# Printing random id using uuid1()
print ("The random id using uuid1() is : ",end="")
print (uuid.uuid1())
#The following can be used to retrieve the MAC ADDRESS which is necessary for #the machine's specific ID
from uuid import getnode as get_mac
mac = get_mac()
#Prevents spoofing of MAC ADDRESS
>>> print uuid.getnode.__doc__
Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4122.

On linux machines, the convention is to read /etc/machine-id. Which is a randomly generated id.

Related

How is the xfer2 function used to read registers using SpiDev?

I'm trying to communicate with my mpu9250 through SPI using the py-spidev module and I'm unable to understand how exactly the read function works.
I found this function snippet that performs the read register function and I'd like to know why the __READ_FLAG (__READ_FLAG = 0x80) is concatenated with the address byte for sending the dummy values to. Won't this change the register address completely?
def ReadReg(self, reg_address):
self.bus.open(self.spi_bus_number, self.spi_dev_number)
tx = [reg_address | self.__READ_FLAG, 0x00]
rx = self.bus.xfer2(tx)
self.bus.close()
return rx[1]
Found the answer for this in another datasheet that follows the same protocol.
Writing is done by lowering CSB and sending pairs control bytes and register data. The control
bytes consist of the SPI register address (= full register address without bit 7) and the write
command (bit7 = RW = ‘0’). Several pairs can be written without raising CSB. The transaction is
ended by a raising CSB.
Reading is done by lowering CSB and first sending one control byte. The control bytes consist
of the SPI register address (= full register address without bit 7) and the read command (bit 7 =
RW = ‘1’). After writing the control byte, data is sent out of the SDO pin (SDI in 3-wire mode);
the register address is automatically incremented.

Get psutil net_io_counters to match values in Network Connection Status

I'm using psutil to query the number of bytes sent and received over ethernet on Windows 10.
I can use psutil.net_io_counters(pernic=True) to get the values. However, when I parse the values I need, they are slightly higher than the byte count that I view in the system UI.
import psutil
network_stats = psutil.net_io_counters(pernic=True)['Ethernet']
bytes_sent = getattr(network_stats, 'bytes_sent')
bytes_recv = getattr(network_stats, 'bytes_recv')
print "Bytes Sent = {0} | Bytes Received = {1}".format(bytes_sent, bytes_recv)
My issue is, the number of bytes returned from this script is always higher than the byte count displayed in the Network Connections -> Ethernet Status UI. However, the difference is relatively small.
Is it possible to use psutil to get the sent/received values to match the Ethernet Status Activity in the screenshot above? And why are the values returned slightly different in the first place?

clingo compiler computing multiple values for #min

I’m having a basic issue whilst using python scripting in ASP / `clingo (Version 4+). I’ve reconstructed the problem with a minimal example, to illustrate the point. Obviously, in the example, I don’t need to use scripts. In my more complicated application, however, I do, whence I have artificially recreated the problem, in a more comprehendible fashion.
The issue is, that whilst calling an aggregate/optimisation, the compiler somehow does not register all the full predicate being used to index the values. Instead, it appears to successively compute the minimum and as a result, spits out all the values along the way. (See the output below: notice that the minimum goes from 59, to 19, then does not change to 29. This is highly sensitive of the order of prg.groundcalls in the #script (python) part of the code.)
This is highly undesirable, and I would like to know how to avoid this problem. I. e., how can I amend the below code still utilising a python-script (potentially modified), so that the correct model is computed. (In the example, obviously, the solution to the predicate min_sel_weight/1 is min_sel_weight(19)with no further values.
The Programme.
weight("ant",3). weight("bat",53). weight("cat",19). weight("dot",13). weight("eel",29).
#script (python)
import gringo;
def main(prg):
prg.ground([('base', [])]);
prg.ground([('sel', ['bat'])]);
prg.ground([('sel', ['cat'])]);
prg.ground([('sel', ['eel'])]);
prg.solve();
#end.
%% call python-script, to select certain objects.
#program sel(t). sel(t).
%% compute minimum of weights of selected objects:
min_sel_weight(X) :- weight(_,X), #min {XX : weight(OBJ,XX),sel(OBJ)} = X.
#show sel/1. #show min_sel_weight/1.
Calling clingo 0 myprogramme.lp I obtain the following output:
clingo version 4.5.4
Reading from myprogramme.lp
Solving...
Answer: 1
sel("bat")
min_sel_weight(53)
sel("cat")
min_sel_weight(19)
sel("eel")
SATISFIABLE
Models : 1
Calls : 1
Time : 0.096s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.040s
Try this:
% instance
weight("ant",3). weight("bat",53). weight("cat",19). weight("dot",13). weight("eel",29).
% Assuming you will get certain selected objects like this:
selected("cat"). selected("bat"). selected("eel"). %this will be python generated
% encoding
selectedWeight(OBJ, XX):- weight(OBJ,XX), selected(OBJ).
1{min_sel_weight(X)}1 :- selectedWeight(_,X), #min {XX : selectedWeight(OBJ,XX),selected(OBJ)} = X.
#show min_sel_weight/1.
Output:

Passing a record over a socket

I have basic socket communication set up between python and Delphi code (text only). Now I would like to send/receive a record of data on both sides. I have a Record "C compatible" and would like to pass records back and forth have it in a usable format in python.
I use conn.send("text") in python to send the text but how do I send/receive a buffer with python and access the record items sent in python?
Record
TPacketData = record
pID : Integer;
dataType : Integer;
size : Integer;
value : Double;
end;
I don't know much about python, but I have done a lot between Delphi, C++, C# and Java even with COBOL.Anyway, to send a record from Delphi to C first you need to pack the record at both ends,
in Deplhi
MyRecord = pack record
in C++
#pragma pack(1)
I don’t know in python but I guess there must be a similar one. Make sure that at both sides the sizeof(MyRecord) is the same length.Also, before sending the records, you should take care about byte ordering (you know, Little-Endian vs Big-Endian), use the Socket.htonl() and Socket.ntohl() in python and the equivalent in Deplhi which are in WinSock unit. Also a "double" in Delphi could not be the same as in python, in Delphi is 8 bytes check this as well, and change it to Single(4 bytes) or Extended (10 bytes) whichever matches.
If all that match then you could send/receive binary records in one shut, otherwise, I'm afraid, you have to send the individual fields one by one.
I know this answer is a bit late to the game, but may at least prove useful to other people finding this question in their search-results. Because you say the Delphi code sends and receives "C compatible data" it seems that for the sake of the answer about Python's handling it is irrelevant whether it is Delphi (or any other language) on the other end...
The python struct and socket modules have all the functionality for the basic usage you describe. To send the example record you would do something like the below. For simplicity and sanity I have presumed signed integers and doubles, and packed the data in "network order" (bigendian). This can easily be a one-liner but I have split it up for verbosity and reusability's sake:
import struct
t_packet_struc = '>iiid'
t_packet_data = struct.pack(t_packet_struc, pid, data_type, size, value)
mysocket.sendall(t_packet_data)
Of course the mentioned "presumptions" don't need to be made, given tweaks to the format string, data preparation, etc. See the struct inline help for a description of the possible format strings - which can even process things like Pascal-strings... By the way, the socket module allows packing and unpacking a couple of network-specific things which struct doesn't, like IP-address strings (to their bigendian int-blob form), and allows explicit functions for converting data bigendian-to-native and vice-versa. For completeness, here is how to unpack the data packed above, on the Python end:
t_packet_size = struct.calcsize(t_packet_struc)
t_packet_data = mysocket.recv(t_packet_size)
(pid, data_type, size, value) = struct.unpack(t_packet_struc,
t_packet_data)
I know this works in Python version 2.x, and suspect it should work without changes in Python version 3.x too. Beware of one big gotcha (because it is easy to not think about, and hard to troubleshoot after the fact): Aside from different endianness, you can also distinguish between packing things using "standard size and alignment" (portably) or using "native size and alignment" (much faster) depending on how you prefix - or don't prefix - your format string. These can often yield wildly different results than you intended, without giving you a clue as to why... (there be dragons).

MAC address generator in python

For purpose of creating bulk virtual machines, I need to create a random MAC address generator in Python. I don't know how to generate random MAC addresses.
Is the following program correct or not?
import random
# The first line is defined for specified vendor
mac = [ 0x00, 0x24, 0x81,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
print ':'.join(map(lambda x: "%02x" % x, mac))
For anyone wanting to generate their own MAC addresses (a good example is for VM NICs), you probably just want this:
"02:00:00:%02x:%02x:%02x" % (random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255))
Or, if you want to do this in a unix'y shell, this works on many:
printf '02:00:00:%02X:%02X:%02X\n' $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256))
This gives you a unicast MAC address that is 100% safe to use in your environment, and isn't trampling on anyone's registered MAC address space.
More detail...
The bottom two bits of the top byte (0x02) give you a locally administered unicast address, which is probably what you want if you are hitting stackoverflow for how to generate this. :)
If the MAC address is not locally administered, it means it is supposed to be "globally unique". MAC addresses in this category are centrally registered with the IEEE, and you should have a unique OUI (Organizationally Unique Identifier) issued to you by the IEEE. See this link for the global registry of OUI values. This OUI value ends up in the first 3 bytes (or just the top 22 bits, really).
MAC addresses aren't that complicated, so you should probably also just have a look at the definition. Wikipedia has a good one.
Modified from mamofish's code to Python3:
mac = '00:00:00:'
for number in range(16**6):
hex_num = hex(number)[2:].zfill(6)
print("{}{}{}:{}{}:{}{}".format(mac,*hex_num))
Generates mac addresses as strings from 00:00:00:00:00:00 to 00:00:00:ff:ff:ff.
Since uniqueness is all you should care about (beyond making the address well-formed), I'd worry about the MSBs in the OUI and use a sequence in the NIC specific bytes. The distribution of the addresses is likely unimportant to your application (even though some NIC or switch implementations might use them as an input to a hash, this is likely not to be a big concern).
You may want to consider using the "locally administered" flag in the OUI to avoid a conflict with an existing device manufacturer.
Avoid pitfalls like setting the multicast bit (your example does).
To avoid duplicates:
If you're going to generate a LOT (millions) of such MAC addresses, you might want to generate an in-order list of MAC's, feed that to a linear randomization process (GNU sort -R should do fine - I don't think it does this in linear time, but it has a similar end result) once, and then pull your fresh addresses off one end of the randomized list as needed. I believe such a list should fit in about 34 megabytes.
If you merely need thousands, you're probably better off maintaining a text file with already-selected values, and checking for collisions against that, adding new values as you go. This is a slower algorithm asympotically speaking, but it has a much less overhead, so it should still be a win for lower numbers of mac addresses.
BTW, should the 4th octet (numbered from 1 starting on the left), be 0-ff instead of 0-7f? I see no occurrences of 7f or 127 in the Wikipedia page on Mac addresses:
http://en.wikipedia.org/wiki/MAC_address

Categories