Génération de fichiers aléatoires dans Windows

Quelqu’un at-il un moyen de générer des fichiers de données aléatoires dans Windows? Je voudrais générer 50 000 petits fichiers (2K) comme exemple.

Vous pouvez exécuter fsutil dans une boucle de traitement par lots pour créer des fichiers de toute taille.

fsutil file createnew filename.extension 2000 

Vous pouvez utiliser PowerShell pour générer des données aléatoires peu coûteuses pour vos fichiers:

 [Byte[]] $out = @() 0..2047 | % {$out += Get-Random -Minimum 0 -Maximum 255} [System.IO.File]::WriteAllBytes("myrandomfiletest", $out) 

Cela utilise un algorithme avec une graine provenant de l’horloge système, ne l’utilisez donc pas pour des applications cryptographiques sérieuses.

En outre, méfiez-vous de la dégradation des performances de Get-Random lorsque vous augmentez la taille du fichier de sortie. Plus sur cet aspect ici:

  • Générateur de fichiers aléatoire PowerShell trop lent
  • Améliorer les performances de Powershell pour générer un fichier aléatoire

J’ai utilisé Random Data File Creator et je l’aime, il crée des fichiers binarys (c.-à-d. Pas de fichiers texte) remplis de bits pseudo-aléatoires, il peut rapidement créer des fichiers très volumineux. Pour l’utiliser pour créer plusieurs petits fichiers, vous devrez le scripter, ce qui serait très simple étant donné qu’il s’agit d’une ligne de commande.

Comme vous ne spécifiez pas de langue, je vais simplement en choisir une au hasard. Voici un script powershell pour le faire:

 $rootDir = 'C:\Temp\TestRandomFiles\' $baseFile = $rootDir + "base.txt" $desiredFileSize = 2*1KB $fileCount = 50000 "start" | Out-File -Filepath $baseFile While ($(Get-ChildItem -path $baseFile).Length -lt $desiredFileSize) { $(Get-ChildItem -path $baseFile).Length | Out-File $baseFile -APPEND } for($i=1;$i -lt $fileCount;$i++) { Copy-Item $baseFile "File$i.txt" } 

Vous devrez changer les variables pour les parameters que vous voulez bien sûr.

Vous devrez créer des fichiers de manière normale, puis les remplir avec des données aléatoires, probablement à partir d’une fonction rand () quelconque.

Cela dépend vraiment de votre langage de programmation. Windows lui-même ne fournira certainement pas cette fonctionnalité.

Il existe toutefois un certain nombre de langages de programmation qui pourraient le faire facilement, y compris les scripts de base Windows batch / CMD. Quelle langue êtes-vous intéressé à utiliser?

One-liner in Powershell:

 $out = new-object byte[] 1048576; (new-object Random).NextBytes($out); [IO.File]::WriteAllBytes('d:\file.bin', $out) 

Cela est très rapide comparé à la solution @ user188737.

Au lieu d’utiliser Get-Random pour générer le texte selon les suggestions de user188737 & mguassa, j’ai amélioré la vitesse en utilisant des GUID.

 Function New-RandomFile { Param( $Path = '.', $FileSize = 1kb, $FileName = [guid]::NewGuid().Guid + '.txt' ) (1..($FileSize/128)).foreach({-join ([guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-").SubSsortingng(1, 126) }) | set-content "$Path\$FileName" } 

Cela a pris 491 millisecondes pour générer un fichier 1mb. Fonctionnement:

 New-RandomFile -FileSize 1mb 

METTRE À JOUR:

J’ai mis à jour ma fonction pour utiliser un ScriptBlock, vous pouvez donc remplacer la méthode ‘NewGuid ()’ par tout ce que vous voulez.

Dans ce scénario, je crée des blocs de 1 Ko, car je sais que je ne crée jamais de fichiers plus petits. Cela a considérablement amélioré la vitesse de ma fonction!

Set-Content force un NewLine à la fin, c’est pourquoi vous devez supprimer 2 caractères à chaque fois que vous écrivez dans un fichier. Je l’ai remplacé par [io.file] :: WriteAllText () à la place.

 Function New-RandomFile_1kChunks { Param( $Path = (Resolve-Path '.').Path, $FileSize = 1kb, $FileName = [guid]::NewGuid().Guid + '.txt' ) $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" } $Chunks = [math]::Ceiling($FileSize/1kb) [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chunk.Invoke() }))") Write-Warning "New-RandomFile: $Path\$FileName" } 

Si vous ne voulez pas que tous les morceaux soient aléatoires, vous pouvez simplement invoquer () la génération du bloc 1kb une fois. Cela améliore considérablement la vitesse, mais ne rendra pas le fichier entier aléatoire.

 Function New-RandomFile_Fast { Param( $Path = (Resolve-Path '.').Path, $FileSize = 1kb, $FileName = [guid]::NewGuid().Guid + '.txt' ) $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" } $Chunks = [math]::Ceiling($FileSize/1kb) $ChunkSsortingng = $Chunk.Invoke() [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $ChunkSsortingng }))") Write-Warning "New-RandomFile: $Path\$FileName" } 

Measure-Command tous ces changements pour générer un fichier 10mb:

Exécution de New-RandomFile: 35.7688241 secondes.

Exécution de New-RandomFile_1kChunks: 25.1463777 secondes.

Exécution de New-RandomFile_Fast: 1.1626236 secondes.

Que diriez-vous de quelque chose comme ceci: Random File Generator 1.1

Ou générateur de fichier

Eh bien, techniquement, vous pourriez écrire quelque chose à faire pour vous.
Je ne connais rien de particulier .. mais le plus simple serait de créer un fichier TEXT d’une taille spécifique (2K par exemple) .. puis d’écrire un fichier batch pour le copier 50000 fois.

Oui, fsutil est génial, mais ne génère pas de données aléatoires, juste des null ASCII.

Je ne me souviens plus où j’ai trouvé cela, mais en cherchant sur Google, je peux toujours le trouver sur: http://www.private-files.com/other/random.c.txt

Je ne sais pas quel âge a ce programme mais au moins aussi vieux que votre question, probablement un peu plus ancienne.

En tout cas, voici un programme en C qui crée des fichiers avec un résultat de test chi-carré de 0:

 // ------------------------------------------------------------ // Name: random.c (program to create random files) // // This "no-frills" program creates files with the following // characteristics: // // (1) Byte sequences are random (no predictability); // (2) Files produced are binary files; // (3) File sizes are multiples of 256; // (4) Files will have a chi-squared test result of 0 // (see analyze.exe by Wenger for explanation) // // Programmer: Scott Wenger // Box 802 // Stevens Point, WI 54481 // [email protected] // // Note: part of this code is from Knuth Volume II // // Enhancements and modifications of this program are left // to the imagination and creativity of the programmer. // Check your comstackr for required header files. You may // need to include the iostream header. // // Random files are of potential use to cryptographers // for the purpose of encryption. // // To analyze files produced by this program, see // the analyze.exe program by Scott Wenger (found at // http://www.coredcs.com/sware.html) // ------------------------------------------------------------ // This program works in the following way: // The time is used to seed the random number generator. // Using Knuth's algorithm, random numbers are generated // in the range of 0 to 255 (corresponding to 256 ASCII chars.) // When random numbers are generated they are marked as used and // are not re-used until all 256 ASCII values appear. Characters // are written to disk and the process continues until the // desired file size is reached. Output is a random binary file // called random.bin (placed in the root directory) // The controlled filesize along with the placeholder feature // of this code forces a very high degree of randomness in // the output file. #include  #include  #include  #include  void init_mm(); void clear_array(); int number_range(int minval, int maxval); int number_mm(); static int rgiState[2 + 55]; int place_holder[256]; // to keep track of numbers already generated int main() { mainprogram(); return 0; } int mainprogram() { int ch; int c_used = 0; // counter of chars in placeholder int done = 0; int random; char buffer[2]; long x; long byte_size = 0L; FILE *fp; clear_array(); init_mm(); // seed random number generator // create a random file of length specified by user printf("\nrandom.exe originally by Scott Wenger"); printf("\nThis program creates a random binary file.\n"); printf("\nPlease specify length of random file to create (in megabytes): "); scanf("%ld", &byte_size); while (byte_size > 1000 || byte_size <= 0 ) { printf("\nWill not create files larger than a gigabyte! "); printf("\nPlease specify length of random file to create (in megabytes): "); flushall(); scanf("%ld", &byte_size); } byte_size = byte_size * 1024 * 1024; if ( (fp = fopen("random.bin", "wb")) == NULL) { fprintf(stderr, "\nOutput file (random.bin) could not be created."); fflush(stdout); exit(1); } for (x = 0L; x < byte_size; x++) { if (c_used == 256) { clear_array(); c_used = 0; } random = number_range(0, 255); // use all ASCII values if ( *(place_holder + random) ) { // already used, find another done = 0; while (!done) { random = number_range(0, 255); if ( *(place_holder + random) == 0) { *(place_holder + random) = 1; done = 1; } } } else *(place_holder + random) = 1; // use it and mark as used c_used++; // found next character so increment counter sprintf(buffer, "%c", random); // convert ASCII value to char ch = buffer[0]; fputc(ch, fp); // write to file } fclose(fp); printf("\nDone. File \"random.bin\" was created (size: %ld bytes)", byte_size); printf("\nOutput file is in the root directory (c:\\random.bin)\n"); return(0); } // --------------------------------------------------------------------------------- void clear_array() { register int x; for (x = 0; x < 256; x++) *(place_holder + x) = 0; } // --------------------------------------------------------------------------------- int number_mm() { int *piState; int iState1; int iState2; int iRand; piState = &rgiState[2]; iState1 = piState[-2]; iState2 = piState[-1]; iRand = ( piState[iState1] + piState[iState2] ) & ( ( 1 << 30 ) - 1 ); piState[iState1] = iRand; if ( ++iState1 == 55 ) iState1 = 0; if ( ++iState2 == 55 ) iState2 = 0; piState[-2] = iState1; piState[-1] = iState2; return(iRand >> 6); } // --------------------------------------------------------------------------------- // Generate a random number. int number_range( int minval, int maxval ) { int power, number; if ( ( maxval = maxval - minval + 1 ) <= 1 ) return (minval); for ( power = 2; power < maxval; power <<= 1 ) ; while ( ( number = number_mm( ) & ( power - 1 ) ) >= maxval ) ; return(minval + number); } // --------------------------------------------------------------------------------- // Mitchell-Moore algorithm from Knuth Volume II. void init_mm( ) { int *piState; int iState; piState = &rgiState[2]; piState[-2] = 55 - 55; piState[-1] = 55 - 24; piState[0] = ( (int) time( NULL ) ) & ( ( 1 << 30 ) - 1 ); piState[1] = 1; for ( iState = 2; iState < 55; iState++ ) { piState[iState] = ( piState[iState-1] + piState[iState-2] ) & ( ( 1 << 30 ) - 1 ); } } // -------------------- End ------------------------------------------------------- 

Vous pouvez utiliser VBA dans Excel si vous disposez d’permissions limitées sur l’ordinateur sur lequel vous vous trouvez. Cela créerait des fichiers txt au nombre requirejs avec des nombres aléatoires. Probablement pas la façon la plus rapide d’y parvenir.

 Sub rndcreate() Application.ScreenUpdating = False Application.DisplayAlerts = False Dim sbook As Workbook Dim i As Double Dim upperbound, lowerbound, totalensortinges, totalfiles As Integer Dim x, folder, file As Ssortingng 'Set output location folder = "C:\test\" 'Number of files created and ensortinges in files as below totalfiles = 1 totalensortinges = 150 upperbound = 99999 lowerbound = 1 For p = 1 To totalfiles 'Add new workbook to populate with data Set sbook = Workbooks.Add 'Set file name file = "randomdatafile" & p For i = 1 To totalensortinges 'Randomly created integers between your two bounds x = ((upperbound - lowerbound + 1) * Rnd + lowerbound) Range("A" & i) = x Next ActiveWorkbook.SaveAs Filename:=folder & file & ".txt", FileFormat:=xlTextWindows ActiveWorkbook.Close Next End Sub 

modifier

Je relis la question, la suivante ne fournira pas la réponse (fichiers 50x2k) tels quels, mais créera des fichiers de taille arbitraire avec des données binarys vraiment aléatoires.

S’il vous plaît commenter si vous souhaitez voir un exemple qui répond exactement à la question.

/modifier

Ce qui suit peut générer un fichier de 1 Go de données aléatoires sécurisées par cryptographie en utilisant des objects disponibles dans Powershell:

 #set the size, 1024^3 = 1GB $size=1024*1024*1024 #as we will build the file 1k at a time, divide required size by 1k $size/=1024 #now create the byte array of a fixed size $bytearray=new-object byte[] 1024 #and create a CSRNG object $RNGObject=new-object Security.Cryptography.RNGCryptoServiceProvider #Create a file for streaming. PS will overwrite if it exists. #its probably bad form to hard code the filename, an exercise for you $stream = New-Object System.IO.FileStream("d:\file1.bin"), Create #open the stream and grab the handle. $writer = New-Object System.IO.BinaryWriter($stream) #create a timer object so we can measure the runtime. start it. $stopwatch=[diagnostics.stopwatch]::startnew() #now, iterate through the required file size 1k at a time 0..($size-1) | Foreach-Object{ #filling our byte array with random non zero bytes $RNGObject.GetNonZeroBytes($bytearray) #and them append them to the file stream. $writer.write($bytearray) } #captain obvious $stopwatch.stop() $stream.close() #and display the stopwatch data $stopwatch IsRunning Elapsed ElapsedMilliseconds ElapsedTicks --------- ------- ------------------- ------------ False 00:00:23.2019782 23201 70240880 

Pour utiliser des données aléatoires avec des valeurs nulles, remplacez simplement

 $RNGObject.GetNonZeroBytes($bytearray) 

avec

 $RNGObject.GetBytes($bytearray) 

Une introduction rapide à duckduckgo, si vous allez sur duckduckgo.com et cherchez avec

 !msdn Security.Cryptography.RNGCryptoServiceProvider 

Vous obtiendrez des résultats extrêmement précis directement depuis Microsoft Developer Network, vous permettant de voir les classes, méthodes et propriétés Crypto disponibles.

J’ai donc décidé d’append une réponse précise cette fois-ci.

la langue est Powershell. hypothèses: les noms de fichiers seront séquentiels et non aléatoires. le contenu du fichier doit être cryptographiquement sécurisé et unique. l’emplacement du fichier doit être C: \ temp \

 #create a fixed size byte array for later use. make it the required file size. $bytearray = New-Object byte[] 2048 #create and start a stopwatch object to measure how long it all takes. $stopwatch = [Diagnostics.Stopwatch]::StartNew() #create a CSRNG object $RNGObject = New-Object Security.Cryptography.RNGCryptoServiceProvider # set up a loop to run 50000 times 0..49999 | Foreach-Object { # create a file stream handle with a name format 'filennnnn' $stream = New-Object System.IO.FileStream("c:\temp\file$("{0:D5}" -f $_)"), Create # and a stream writer handle $writer = New-Object System.IO.BinaryWriter($stream) # Fill our array from the CSRNG $RNGObject.GetNonZeroBytes($bytearray) # Append to the current file $writer.write($bytearray) # Close the stream $stream.close() } # how long did it all take? $stopwatch.stop() $stopwatch 

Et la sortie:

 IsRunning Elapsed ElapsedMilliseconds ElapsedTicks --------- ------- ------------------- ------------ False 00:07:53.7685350 473768 1434270755 

Mmm, on a l’impression que ça a pris du temps, mais

 $stopwatch.ElapsedMilliseconds/50000 9.47536 

Donc, c’est environ 10 ms par fichier. C’est un vieux disque sata.