Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read /dev/random in python

Tags:

python

unix

I read in a book that /dev/random is like an infinite file, but when I set up the following codes to see what the content look like, it prints nothing.

with open("/dev/random") as f:
    for i in xrange(10):
        print f.readline()

BTW, when I tried this with /dev/urandom, it worked.

like image 339
satoru Avatar asked Jun 26 '12 04:06

satoru


People also ask

How does urandom work Python?

urandom() method is used to generate a string of size random bytes suitable for cryptographic use or we can say this method generates a string containing random characters. Return Value: This method returns a string which represents random bytes suitable for cryptographic use.

What does Dev random do?

The /dev/random device is intended to provide high quality, cryptographically secure random output and will only return output for which sufficient (an equal or greater amount) random input is available to generate the output.

How random is Dev urandom?

Using /dev/random may require waiting for the result as it uses so-called entropy pool, where random data may not be available at the moment. /dev/urandom returns as many bytes as user requested and thus it is less random than /dev/random .

Why does Dev random block?

In those older kernels, /dev/random would block because the blocking entropy pool had been depleted. However, changes to the algorithms used in ealier kernels meant that there was no longer any useful distinction between the blocking and non-blocking entropy pools.


2 Answers

FWIW, the preferred way of accessing this stream (or something like it) in a semi-portable way is os.urandom()

like image 92
Raymond Hettinger Avatar answered Sep 21 '22 10:09

Raymond Hettinger


It is outputting random bytes, not random lines. You see nothing until you get a newline, which will only happen every 256 bytes on average. The reason /dev/urandom appears to work is simply that it operates faster. Wait longer, read less, or use /dev/urandom.

like image 25
tripleee Avatar answered Sep 19 '22 10:09

tripleee