tags:

views:

66

answers:

3

Does anyone have a simple shell script or c program to generate random files of a set size with random content under linux?

+6  A: 

How about:

head -c SIZE /dev/random > file
Carl Norum
If you can sacrifice some entropy you can also use /dev/urandom instead. It will be faster since it will not block waiting for more environmental noise to occur
Alexandre Jasmin
Good suggestion. Yes it doesn't need to be perfectly random at all.
Matt H
Perfect. does the job.
Matt H
If you somehow find yourself needing to read from /dev/random and it's blocking due to lack of sufficient randomness one reasonable way to get some more is to run a 'du /'. This gets the disk moving and generated some extra entropy (not guaranteed for flash drives).
Paul Rubel
When I run `head -c 1024 /dev/random > file`, it seems like it was waiting something to complete and never finish writing to my file, what may be the problem?
Satoru.Logic
@Satoru Logic Read what myself and @paulrubel wrote in the comments above
Alexandre Jasmin
A: 

Python. Call it make_random.py

#!/usr/bin/env python
import random
import sys
import string
size = int(sys.argv[1])
for i in xrange(size):
    sys.stdout.write( random.choice(string.printable) )

Use it like this

./make_random 1024 >some_file

That will write 1024 bytes to stdout, which you can capture into a file. Depending on your system's encoding this will probably not be readable as Unicode.

S.Lott
A: 

Here's a quick an dirty script I wrote in Perl. It allows you to control the range of characters that will be in the generated file.

#!/usr/bin/perl

if ($#ARGV < 1) { die("usage: <size_in_bytes> <file_name>\n"); }

open(FILE,">" . $ARGV[0]) or die "Can't open file for writing\n";

# you can control the range of characters here
my $minimum = 32;
my $range = 96;

for ($i=0; $i< $ARGV[1]; $i++) {
    print FILE chr(int(rand($range)) + $minimum);
}

close(FILE);

To use:

./script.pl file 2048

Here's a shorter version, based on S. Lott's idea of outputting to STDOUT:

#!/usr/bin/perl

# you can control the range of characters here
my $minimum = 32;
my $range = 96;

for ($i=0; $i< $ARGV[0]; $i++) {
    print chr(int(rand($range)) + $minimum);
}

Warning: This is the first script I wrote in Perl. Ever. But it seems to work fine.

quantumSoup