Batch program

honggarae 12/03/2022 953

Introduction

Thereisnofixedformatforthecompositionofthebatchprogram,aslongasthefollowingisfollowed:eachlinecanberegardedasacommand,andeachcommandcancontainmultiplesubcommands.Executefromthefirstlineuntiltheendofthelastline.TheplatformitrunsonisDOS.Batchprocessinghasaverydistinctivefeature:easytouse,flexible,highdegreeofautomation,butthefunctionisrelativelyweak.Idon'twanttomakethetutorialsIwriteboring,becausetheproblemsthatinvolvecode(thecontentofbatchprocessingiscode?)areinherentlyboring,andfewpeoplecancalmdowninthefaceoffull-screencode.SoIwillusealotofsimpleandpracticalexamplestoletfriendswhoreadthistutorialexperiencetheradiantcharmofbatchprocessing,feelitsquirkycharacter,andfallinlovewithbatchprocessingunknowingly(Halo,howisloveagain?Whatistherelationshipbetweenbatchprocessingandlove?Answer:No!).Letmetalkabout"gossip":Tolearnbatchprocessingwell,youmusthaveafirmfoundationinDOS!Ofcourse,beingflexibleisalsoaveryimportantaspect.

Thefunctionofbatchprocessingdependsentirelyonthecommandsyouuse,andbatchprocessingcommandsaredividedintointernalcommandsandexternalcommands,aswellassomethird-partytools.

ThemostcommonlyusedbatchfileisAUTOEXEC.BATfile,nomatterwhenthesystemisstartedorrestarted,DOSwillautomaticallyexecuteit.Thisfileallowsyoutodothefollowingthings:inputthecurrentdate,setthecommandpathandthesystempromptandloadtheprogramwithouthavingtotypeeachcommandseparately.AUTOEXEC.TheBATfilemustbelocatedintherootdirectoryofthebootDOSdisk.

Allbatchesareprocessedin.BATor.CMDastheextension,butyoudon’tneedtotypetheextensiononthecommandlinewhenyourunthefile.Toexecuteabatchfile,simplytypeitsfilenameatthesystemprompt,andDOSwillexecutethecommandscontainedinthebatchfileinorder.

Togiveafewexamples,forexample,whenyouneedtouseDOScommandswhenyouinstallanewcomputer,youneedtoinstallthesystembytypingcommands;ifyoucanstringallthecommandstogether,letitAutomatically,thentheinstallationworkwillbecomeveryautomated.Thiskindofchainedcommandsisbatchprocessing.Inthisway,manycommandsareassembledintoonefile,andtheexecutablefilethatcompletestheautomationtaskisabatchfile.BatchfilesgenerallyuseBATastheextension.Let'stakeanotherexampletoillustratethecreationofbatchfilesandtheiruseintheWindowsenvironment.Forexample,ifwewanttocreate8foldersunderacertainfolder,theirnamesareMULU1,MULU2...MULU8,etc.,wecanuse"Notepad"tocreateafileMAKE.BATinthisfolderfirst(note:IftheextensionisBAT,notTXT),theneditthisfile,anditscontentissuchas:

MDMULU1

MDMULU2

……

MDMULU8

Wait8linesofcontent,aftereditingandsaving,aslongaswedouble-clickthecreatedMAKE.BATfile,8folderswillbeautomaticallycreatedforus.

Concisebatchprocessingtutorial

Ajumailpublishedon2005-03-11

Recently,thediscussiononbatchprocessingtechnologyisrelativelyhot,andtherearemanygoodbatchprocessing.Theprogramisreleased,butifyoudon’thavecertainrelevantknowledge,it’sprobablynoteasytoreadandunderstandthesebatchfiles,letalonewriteityourself.Theoldsayinggoes:“Teachingpeopletofishisbetterthanteachingpeopletofish.”BecauseTheredoesnotseemtobearelativelycompletetextbookontheInternet,soItookamomenttowritethistonewbiefriends.ItisalsodedicatedtoallfriendswhoareworkinghardtorealizethefreedomandsharingoftheInternet.

Batchfilesareunformattedtextfilesthatcontainoneormorecommands.Itsfileextensionis.bator.cmd.Typethenameofthebatchfileatthecommandprompt,ordouble-clickthebatchfile,andthesystemwillcallCmd.exetoruneachcommandinthefileintheorderinwhichitappears.Usingbatchfiles(alsocalledbatchprogramsorscripts)cansimplifydailyorrepetitivetasks.Ofcourse,themaincontentofthisversionofoursistointroducesomepracticalapplicationsofbatchprocessinginintrusions,forexample,wewillusebatchfilestopatchthesystemandimplantbackdoorprogramsinbatchesaswewillmentionlater.Let'sstartourbatchlearningjourney.

Simpleinternalcommand

Echocommand

Turnonorturnofftherequestechofunction,ordisplayamessage.Iftherearenoparameters,theechocommandwilldisplaythecurrentechosettings.

Syntax

echo[{on|off}][message]

Sample:@echooff/echohelloworld

InInpracticalapplications,wewillcombinethiscommandwiththeredirectionsymbol(alsoknownasthepipesymbol,usuallywith>>>^)toinputsomecommandsintoafileofaspecificformat.ThiswillbeinthefollowingexamplesReflected.

@Command

Itmeansthatthecommandsfollowing@arenotdisplayed.Naturally,duringtheinvasionprocess(forexample,usingbatchprocessingtoformattheenemy’sharddisk),theotherpartywillnaturallynotbeabletolettheotherpartyseethecommandsyouuseLa.

Sample:@echooff

@echoNowinitializingtheprogram,pleasewaitaminite...

@formatX:/q/u/autoset(Theformatcommandcannotusethe/yparameter.Fortunately,Microsofthasleftanautosetparameterforus.Theeffectisthesameas/y.)

Gotocommand

specifiestojumptothelabel.Afterthelabelisfound,theprogramwillprocessthecommandstartingfromthenextline.

Syntax:gotolabel(labelisaparameter,whichspecifiesthelineinthebatchprogramtobetransferred.)

Sample:

if{%1}=={}gotonoparms

if{%2}=={}gotonoparms(Ifyoudon’tunderstandif,%1,%2here,skiptoitfirst,andtherewillbeadetailedexplanationlater.)

@Remcheckparametersifnullshowusage

:noparms

echoUsage:monitor.batServerIPPortNumber

gotoend

Thenameofthetagcanbearbitrary,butitisbesttohaveameaningfulletter,addaletterbeforetheletter:toindicatethattheletterisalabel,thegotocommandisbasedonthis:tofindthenextstepandjumpthere.It’sbesttohavesomeexplanationsothatothersseemtounderstandyourintentions.

Remcommand

Commentcommand,whichisequivalentto/*--------*/inClanguage,itwillnotbeexecuted,justacommentFunction,easyforotherstoreadandmodifylaterbyyourself.

RemMessage

Sample:@RemHereisthedescription.

Pausecommand

WhenthePausecommandisrun,thefollowingMessage:

Pressanykeytocontinue...

Sample:

@echooff

:begin

copya:*.*d:\back

echoPleaseputanewdiskintodriverA

pause

gotobegin

Inthisexample,allfilesonthediskindriveAarecopiedtod:\back.WhenthedisplayedcommentpromptsyoutoputanotherdiskintodriveA,thepausecommandwillsuspendtheprogramsothatyoucanreplacethedisk,andthenpressanykeytocontinueprocessing.

Callcommand

Callanotherbatchprogramfromonebatchprogramwithoutterminatingtheparentbatchprogram.Thecallcommandacceptsalabelusedasthetargetofthecall.IfyouuseCalloutsideofascriptorbatchfile,itwillnotworkonthecommandline.

Syntax

call[[Drive:][Path]FileName[BatchParameters]][:label[arguments]]

Parameters

[Drive:}[Path]FileName

Specifythelocationandnameofthebatchprogramtobecalled.Thefilenameparametermusthavea.bator.cmdextension.

startcommand

Callexternalprograms,allDOScommandsandcommandlineprogramscanbecalledbythestartcommand.

Commonintrusionparameters:

MinimizethewindowatthebeginningofMIN

SEPARATEStarta16-bitWindowsprograminaseparatespace

HIGHStarttheapplicationintheHIGHprioritycategory

REALTIMEStarttheapplicationintheREALTIMEprioritycategory

WAITStarttheapplicationandwaitforittoend

parametersThesearetransmissionsParameterstocommand/program

Whentheexecutedapplicationisa32-bitGUIapplication,CMD.EXEwillreturntothecommandpromptwithoutwaitingfortheapplicationtoterminate.Ifexecutedwithinacommandscript,thisnewbehaviorwillnotoccur.

choicecommand

choiceUsethiscommandtoallowuserstoenteracharactertorundifferentcommands.The/c:parametershouldbeaddedwhenusingit,andthecharactersthatcanbeinputshouldbewrittenafterc:,andthereisnospacebetweenthem.Itsreturncodeis1234......

Suchas:choice/c:dme/mdefrag,mem,end

willdisplay

defrag,mem,end[D,M,E]?

Sample:

ThecontentofSample.batisasfollows:

@echooff

choice/c:dmedefrag,mem,end

iferrorlevel3gotodefrag(Theerrorcodewiththehighestvalueshouldbejudgedfirst)

iferrorlevel2gotomem

iferrotlevel1gotoend

Batch program

:defrag

c:\dos\defrag

gotoend

:mem

mem

gotoend

:end

echogoodbye

Afterthisfileisrun,itwilldisplaydefrag,mem,end[D,M,E]?Theusercanselectdme,andthentheifstatementwillmakeajudgment.dmeanstoexecutetheblocklabeleddefrag,mtoexecutetheblocklabeledmem,andetoexecutetheblocklabeledend.Attheendofeachprogramsegment,jumptheprogramtotheendlabelwithgotoend,andthentheprogramwilldisplaygoodbye,andthefileends.

Ifcommand

ifmeansthatitwilljudgewhetherthespecifiedconditionsaremet,andthendecidetoexecutedifferentcommands.Therearethreeformats:

1,if"parameter"=="string"Thecommandtobeexecuted

Iftheparameterisequaltothespecifiedstring,theconditionisestablished,andthecommandisexecuted,otherwiseRunthenextsentence.(Notethattherearetwoequalsigns)

Suchasif"%1"=="a"formata:

if{%1}=={}gotonoparms

if{%2}=={}gotonoparms

2,ifexistfilenametobeexecutedcommand

Ifthereisaspecifiedfile,thentheconditionisestablishedandrunCommand,otherwiserunthenextsentence.

Suchasifexistconfig.syseditconfig.sys

3,iferrorlevel/ifnoterrorlevelnumberthecommandtobeexecuted

IfthereturncodeisequaltothespecifiedNumber,theconditionismet,runthecommand,otherwiserunthenextsentence.

Suchasiferrorlevel2gotox2

WhentheDOSprogramruns,itwillreturnanumbertoDOS,whichiscalledtheerrorcodeerrorlevelorreturncode.Thecommonreturncodesare0and1.

forcommand

Theforcommandisamorecomplicatedcommand,mainlyusedforparameterstoexecutecommandsinaspecifiedrangeinaloop.

WhenusingtheFORcommandinabatchfile,pleaseuse%%variabletospecifythevariable

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

%variablespecifiesasingle-letterreplaceableparameter.

(set)Specifyoneoragroupoffiles.Youcanusewildcards.

commandspecifiesthecommandtobeexecutedoneachfile.

command-parametersspecifiesparametersorcommandlineswitchesforspecificcommands.

WhenusingtheFORcommandinabatchfile,pleaseuse%%variable

insteadof%variabletospecifythevariable.Variablenamesarecasesensitive,so%iisdifferentfrom%I

Otherinformation

Ifthecommandextensionisenabled,thefollowingadditionalFORcommandformatwillbeaffected

Support:

FOR/D%variableIN(set)DOcommand[command-parameters]

Ifwildcardcharactersareincludedintheset,specifythedirectorynametomatchinsteadofFile

Namematches.

FOR/R[[drive:]path]%variableIN(set)DOcommand[command-

Checkthedirectorytreerootedat[drive:]path,pointingtoeach

FORstatementsindirectories.Ifnodirectoryisspecifiedafter/R,thecurrent

directorywillbeused.Ifthesetisonlyasingledot(.)character,thedirectorytreeisenumerated.

FOR/L%variableIN(start,step,end)DOcommand[command-para

Thissetrepresentsasequenceofnumbersfromstarttoendinincrements.

Therefore,(1,1,5)willproducethesequence12345,and(5,-1,1)willproducethesequence(54321).

FOR/F["options"]%variableIN(file-set)DOcommand

FOR/F["options"]%variableIN("string")DOcommand

FOR/F["options"]%variableIN(command)DOcommand

Or,ifthereisausebackqoption:

FOR/F["options"]%variableIN(file-set)DOcommand

FOR/F["options"]%variableIN("string")DOcommand

FOR/F["options"]%variableIN(command)DOcommand

filenamesetisoneormorefilenames.Beforecontinuingtothenextfileinfilenameset,eachfilehasbeenopened,read,andprocessed.

Processinginvolvesreadingafile,dividingitintolinesoftext,andthenparsingeachlineintozeroormoresymbols.Thenusethefoundsymbolstringvariablevalue

tocalltheForloop.Bydefault,/Fpassesthroughthefirstblanksymbolthatseparates

ineachlineofeachfile.Skipblanklines.Youcanoverridethedefaultparsingoperationbyspecifyingoptional"options"

parameters.Thisquotedstringincludesoneormore

keywordsthatspecifydifferentparsingoptions.Thesekeywordsare:

eol=c-referstotheendofalinecommentcharacter(justone)

skip=n-referstothenumberoflinesignoredatthebeginningofthefile.

delims=xxx-Referstothedelimiterset.Thisreplacesthespaceandtabkeys

Thedefaultdelimiterset.

tokens=x,y,m-n-Referstowhichsymbolofeachlineispassedtotheforitselfofeachiteration

.Thiswillcausetheformatoftheextravariablenametobearange.Specifym

thelastcharacterasteriskinthesymbolstringthroughthenthsymbol,

Thenadditionalvariableswillbeallocatedandassignedafterthelastsymbolanalysis

Acceptthereservedtextoftheline.

usebackq-Specifiesthatthenewgrammarhasbeenusedinthefollowingsituations:

Executeastringofbackquotesasacommandand

ThequotationmarkcharacterisaliteralstringCommandandallowtheuseofdoublequotationmarkstoexpandthefilenameinfi

.

sample1:

FOR/F"eol=;tokens=2,3*delims=,"%iin(myfile.txt)docommand

Eachlineinmyfile.txtwillbeanalyzed,andthoselinesbeginningwithasemicolonwillbeignored,andthesecondandthirdsymbolsineachlinewillbepassedtotheforprogrambody;usecommasand/or

Spacedelimitersymbol.Pleasenotethatthestatementofthisforprogrambodyrefersto%itogetthesecondsymbol,%jtogetthethirdsymbol,and%k

togetthethirdsymbolAllremainingsymbolsaftersymbols.Forfileswithspaces

name,youneedtoenclosethefilenameindoublequotes.Inordertousedoublequotationmarksinthisway,youalsoneedtousetheusebackqoption,otherwise,doublequotationmarkswillbeinterpretedasdefiningacharactertobeanalyzed.Skewered.

%iisspecificallyexplainedintheforstatement,and%jand%karespecificallyexplainedthroughthe

tokens=option.Youcanspecifyupto26symbolsviatokens=oneline

,aslongasyoudon’ttrytospecifyavariablehigherthantheletterzor

Z.Remember,theFORvariableisasingleletter,case-sensitiveandglobal;

Atthesametime,therecannotbemorethan52inuse.

YoucanalsouseFOR/Fanalysislogiconadjacentstrings;themethodis,

Enclosethefilenamesetbetweentheparenthesesinsinglequotes.Inthisway,thestringofcharacters

willbetreatedasasingleinputlineinafile.

Finally,youcanusetheFOR/Fcommandtoanalyzethecommand.

Onepointmustbepointedout:ThechoicecommandinArticle8isnolongeravailableunderthenewversionofWindows,youcanuseset/Replacethepcommand,andthenmakeajudgmentoperationbasedontheinput.

Latest: Fiber paper

Next: CIA