2010-08-09 79 views

回答

13

如何:

head -c SIZE /dev/random > file 
+3

如果你可以犧牲一些熵,你也可以改用/ dev/urandom。它會更快,因爲它不會阻止等待更多的環境噪音發生 – 2010-08-10 00:02:54

+0

好的建議。是的,它不需要完全隨機。 – Matt 2010-08-10 00:08:34

+0

完美。做這項工作。 – Matt 2010-08-10 00:10:31

0

的Python。說它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)) 

使用方法如下

./make_random 1024 >some_file 

那會寫1024個字節到stdout,你可以捕捉到一個文件中。根據您的系統編碼,這可能不會像Unicode一樣可讀。

0

這是我在Perl中編寫的一個快速骯髒的腳本。它允許您控制將生成的文件中的字符範圍。

#!/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); 

要使用:

./script.pl file 2048 

這裏有一個較短的版本的基礎上,輸出到標準輸出S.洛特的想法:

#!/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); 
} 

警告:這是我在Perl中編寫的第一個腳本。永遠。但它似乎工作正常。

0

您可以使用我的generate_random_file.py腳本(Python 3)來生成我的項目中的測試數據。

  • 它適用於Linux和Windows。
  • 它速度非常快,因爲它使用os.urandom()來生成256 KiB塊的隨機數據,而不是分別生成和寫入每個字節。
3

openssl rand可用於生成隨機字節。 的命令是如下:

openssl rand [bytes] -out [filename]

例如,openssl rand 2048 -out aaa將生成一個名爲aaa文件含有2048隨機字節。

2

這裏有幾個方面:

的Python:

RandomData = file("/dev/urandom", "rb").read(1024) 
file("random.txt").write(RandomData) 

擊:

dd if=/dev/urandom of=myrandom.txt bs=1024 count=1 

使用C:

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int byte_count = 1024; 
    char data[4048]; 
    FILE *fp; 
    fp = fopen("/dev/urandom", "rb"); 
    fread(&data, 1, byte_count, fp); 
    int n; 

    FILE *rand; 
    rand=fopen("test.txt", "w"); 
    fprintf(rand, data); 
    fclose(rand); 
    fclose(rand); 
} 
+0

我不認爲C代碼是有效的。如果你嘗試運行它,你會得到一個coredump。 – schaiba 2016-08-09 06:37:00