如何通过CMD从文本文件插入密码及自动解锁加密RAR文件?
Alright, let's tackle your two questions step by step—no manual typing required once we set this up!
First up, how to read a password stored in a text file and feed it into a CMD command. There are two common ways to do this, depending on the tool you're using:
Method 1: Store the password in a variable
This works great for tools that accept password parameters directly. First, read the password into a CMD variable, then pass that variable to your command::: Read the first line of password.txt into the "pass" variable set /p pass=<password.txt :: Use the variable in your command (example with a hypothetical tool) some-tool.exe -u myusername -p %pass%Important: Make sure your
password.txtonly contains the password (no extra spaces or newlines at the end)—otherwise the variable will include those extra characters and your password will fail.Method 2: Pipe the password directly to the tool
For tools that prompt for a password interactively, you can pipe the content of the text file straight into the tool's input:type password.txt | some-interactive-tool.exeThis sends the password as if you typed it manually when the tool asks.
To do this, you'll need a command-line archive tool like WinRAR or 7-Zip (CMD can't natively handle RAR files). Here's how to set it up for both options:
Using WinRAR
First, ensure WinRAR's rar.exe is in your system's PATH (or use the full path, like C:\Program Files\WinRAR\rar.exe).
Option 1: Use a variable (clean and reliable)
:: Read password from file set /p pass=<password.txt :: Extract the RAR file ("x" keeps folder structure; use "e" to extract all files to current directory) rar x -p"%pass%" your-protected-file.rarThe
-p"%pass%"flag tells WinRAR to use the password stored in the variable. Quoting%pass%ensures special characters (like!@#$) don't break the command.Option 2: Pipe the password directly
WinRAR supports reading the password from standard input with the-p-flag:type password.txt | rar x -p- your-protected-file.rarThis works just like the interactive pipe method—WinRAR grabs the password from the text file instead of asking you to type it.
Using 7-Zip (Alternative)
If you prefer 7-Zip, the syntax is similar:
set /p pass=<password.txt 7z x your-protected-file.rar -p"%pass%"
Or with piping:
type password.txt | 7z x your-protected-file.rar -p-
Quick Safety & Usage Notes
- Always double-check your
password.txt—even a single extra newline or space will make the password invalid. - Storing passwords in plain text is a security risk. Only use these methods for personal use or in a fully secure environment.
内容的提问来源于stack exchange,提问作者Mans1

