Tải bản đầy đủ - 0 (trang)
Chapter 23. Automating Tasks Using Windows Server 2003 Scripting

Chapter 23. Automating Tasks Using Windows Server 2003 Scripting

Tải bản đầy đủ - 0trang

includingsomecommand-lineutilitiesandscriptswrittenusing

theMicrosoftVisualBasicScriptinglanguageknownas

VBScript.Thischapteralsocoverssomebasicscripting

commandsandprovidessomeexamplesusingWMI,ADO,CDO,

andADSIobjectmodelstomanagetheWindowsServer2003

environment.Thepurposeofthischapteristohelp

administratorsthinkofwaystosimplifyadministrativetasksby

creatingscripts.







ScriptingOverview

Whenaprojectortaskinvolvingscriptingcomesaround,many

administratorscringeatthethought.Administratorsnewinthe

ITfieldassociatescriptingwithprogrammingorcreating

applications.Inmanyinstances,thatisthecase.However,

manyadministratorsmayalreadybeusingorevencreating

scriptsalthoughtheydisregardsuchscriptssimplybecause

theyweretooeasytocreateordidnothaveloopsofcodeor

fancyoutput.Forexample,manyadministratorscreatelogin

scriptsbutdon'tconsiderthistasktobescriptingbecausethe

scriptsmayjustbesimplebatchfilestomapnetworkdrives.If

afileautomaticallyexecutesseveralcommandssequentiallyor

simultaneously,itisascript.

Scriptingshouldnotbecategorizedonlyasprogrammingunless

theuseofthescriptdefinesitthatway.Scriptscanbecreated

tobreakdownlargeorcomplicatedprocessesintomanysimple

tasks,suchasachecklistthatcanbefollowedtostepsomeone

throughtheentireprocess.Agoodexampleofascript

unrelatedtocomputingandnetworkingisacookingrecipe.If

youfollowthestepsintherecipe,theresultcouldbringa

deliciousmeal.Ascriptthatautomatestheprocessofcreating

severalhundreduseraccountscanreducethetimenecessary

tocompletethetaskandalsoreducehumanerrorbecausethe

inputdatacanbereadfromafileasopposedtobeingtyped

manually.

ITadministratorscanconfigureanumberofscriptsthatprovide

somelevelofautomationwhenitcomestomanaginghardware,

software,groups,anduseraccountswithinanorganization.

Scriptscanbeclassifiedinanumberofways,suchas

documentedinstructionguides,servermanagementscripts,

workstationmanagementscripts,directorymanagement

scripts,andapplicationmanagementscripts.Usersmayalso

haveseparateconfigurationscripts,includinglogonandlogoff



scripts.



DocumentedInstructionScripts

Adocumentedinstructionscriptisgenerallyfairlybasicin

nature.Usually,thisscriptisusedbyadministrators,endusers,

orpersonnelasaninstructionguideorastep-by-stepscript

thatneedstobefollowedtoperformatask.Forexample,this

typeofscriptcouldtestanapplication'sfunctionality;itmay

alsobecalledaqualityassurancescript.Thefollowingscript,

forexample,canbeusedbyhelpdeskpersonneltoverifybasic

operationofthedomainnamesystem:

1. Logontoaserverorworkstationwithaccesstothenetwork

withtheDNSserver.

2. ChooseStart,Run.

3. Typecmd.exeandclickOKtoopenacommandprompt.

4. TypeNslookupandpressEnter.

5. TypeServerfollowedbythenameoftheDNSserveryou

wanttotest.Forexample,typeServerns1.companyabc.com.Then

pressEnter.

6. TypeinanInternetrecord,suchaswww.microsoft.com,

andpressEnter.

7. Ifananswerisdisplayed,typequit.Thentypeexittoclose

thecommandprompt.



Althoughtheprecedingisreallyjustastep-by-stepguide,itis

alsoascript,executedmanually.Itisascriptthatchecks



whethertheDNSservercanresolveInternetDNSrecords.

Thesetypesofscripts,dependingontheskilllevelsofyourstaff

andthescopeofthedocument,maybestbecreatedbyITstaff

andthenformatted,standardized,andcleanedupbya

technicalwriter.Oneofthebiggestfactorsforscripted

instructionsisthelevelofdetailnecessary.Thisdetailisdefined

bythetargetaudience.Forexample,iftheprecedingscript

werewrittenforanadministratorwithareasonableamountof

knowledgewithDNS,thescriptmaysimplybe:

PerformaDNSlookupofanexternalInternetaddress

usingns1.companyabc.comtoverifyInternetnameresolution.

Thestepsherearepresentedsothatapersonwhohasonly

basiccomputerskillscanperformthetask.

Commonscriptsthatorganizationsmaybenefitfromarethose

thatshutdownandrestartaserver.Backinthedayswhen

remoteservermanagementwasverylimited,ifaserver

crashedandtheadministratorwasnotonsite,thistypeof

documentcouldassistonsitepersonnelincompletingthe

necessarytaskofrebootingtheserverinsteadofhavingtowait

fortheadministratortoreturn.



ServerManagement

Servermanagementscriptscomeinafewflavors.Scriptscan

bewrittentocollectinformationstoredintheRegistry,onthe

harddrive,orintheBIOS.Informationsuchashowlongthe

serverhasbeenrunning,howmuchfreediskspaceremains,

andhowmanyusersareusingapplicationsandservicessuchas

fileshares,printers,orterminalserversessionscanbecollected

andanalyzed.Filesandprintersharescanbecreatedand

configuredremotelywithoutuserintervention,andNTFS



permissionscanbecheckedandupdatedusingascript.

Ascriptcanbecreatedtoconnecttoaserverorlistofservers,

andeachservercanbeshutdown,rebooted,orhaveaservice

restarted.Therearereallyfewlimitationsonwhatcanbe

performedonaserverusingascript.Forthemostfunctionality

whenitcomestomanagingWindowsServer2003systems,

MicrosoftWindowsManagementInstrumentation(WMI)may

providethemostextensivefunctionality.



WorkstationManagement

Workstationmanagementisnotreallydifferentfromserver

managementinthewayscriptscanbeused.Tasksthatcanbe

performedonworkstationsratherthanonserversareupdating

securitypatchesandrestartinganumberofmachines.Other

examplesmightbesendingoutpop-upmessagestoall

workstationsonthenetworkthatwillbeaffectedbyaserver

thatisgoingoffline,ortellinguserstosavedatabeforebattery

backuppowerrunsoutduringanextendedpoweroutage.



ScriptsforUserConfiguration

Scriptstomanageusersincludelogonandlogoffscripts

primarily.Logonandlogoffscriptscanbeusedtoconnectand

disconnectnetworkprintersandnetworkfileshares,clearout

oldtemporaryfiles,orsavedatastoredinalocalfolderupto

theserver.Advancedfeaturesoflogonscriptscaninclude

incorporatingcommand-lineexecutablesandVisualBasicScript

commandstoconnecttoresourcesbasedongroup

membership,createemailprofiles,configureinstantmessenger

settings,andrecordlogonandlogoffstatistics.



DirectoryAdministrationScripts

Directoryadministrationscriptscanperformmanytasksthat

benefitadministratorsatalllevelsoftheIThierarchy.Script

usagecanincludesearchingdirectories,creatinguseraccounts,

addingmemberstogroups,andmuchmore.Tomanageuser

objectsinadirectory,youcancreateascripttoscanthe

directoryforlocked-outordisableduseraccounts.Scriptscan

checkwhethernewaccountswerecreatedduringacertain

periodoftimeanddeterminewhichaccountstheyare.

Somecommonlycreateddirectoryadministrationscriptsinclude

scriptstoreadfromfilesfordirectoryimportsandcreateoutput

filestoupdateseparatedirectories.Userinformationcanbe

synchronizedoroverwrittenfrominformationstoredinseparate

directories.Objectsthatcommonlyaresynchronizedbetween

directoriesareuserobjectsandproperties,andgroupobjects

andtheirmembers.

Manyorganizationscreatedirectoryscriptstogivelower-level

administratorsandendusersawaytomanageandaccesstheir

particulardirectoryobjectorsetofobjects.Forexample,a

scriptcouldbewrittenforanemployeeintheHumanResources

departmentwhoneededtohavetheabilitytocreateuser

accountsandmodifycontactinformationforallexisting

employeesinthedirectory.Withoutthebenefitofscripting,this

processwouldhavetobeperformedbyloadingthe

administrativetoolsontheHRuser'sdesktopandthentraining

himhowtocreateusersandhowtolocateusersusingthetool.

Thiswouldbeatediousalternativeandwouldgivetheuser

accesstomoreinformationthanisnecessary.

Abetteralternativewouldbecreatingafewsimplescriptsone

tocreateauserandanothertofindanexistinguserinthe

directory.ThescriptswouldbeusedtoprovideanHTMLor

VisualBasicinterfaceforanHRmanagertoupdateemployee

contactdata.Onlyminimaldatawouldbenecessaryforuser



creation,andseveralfieldscanbepopulatedfromthat

information.Forexample,iftworequiredfieldswereLocation

andDepartment,thisdatacouldbeusedtodeterminegroup

membership,homefolderserver,profilelocation,andlogon

script.Tosimplifylookinguporeditinginformation,youcan

createpull-downmenustolimittheHRmanager'soptions.As

anaddedbonustotheusercreationscript,theuseraccount

couldbesettorequireapasswordchangeatnextlogon.



AdvantagesofScripting

Thischapterfocusesonautomatingusermanagement,

computermanagement,andserveradministrationtasks.The

scriptinglanguageVBScriptwillbeusedthroughoutthischapter

alongwithafewothertechnologies,includingActiveXData

Objects(ADO)andWindowsManagementInstrumentation

(WMI).Afewadvantagesofusingscriptstoperformrepetitive

ortedioustasksisthathumanerrorisreducedbecausescripts

willneverskipasteporincorrectlytypeindatawhen

synchronizinginformation,orevenworse,stopaserviceto

performamaintenancetaskandforgettostartitupafterward.

Scriptsthatwillbedeployedtoautomatetasksshouldbe

completelytestedinalabenvironmentbeforebeingdeployedin

aproductionenvironment.







IntroductiontoVBScript

VBScriptisoneofthetwoscriptinglanguagescreatedby

Microsoft.Forthescriptsinthischapter,VBScriptwillbeused.

Itisnotareplacementforafullprogramminglanguagesuchas

VisualBasic.NETorVisualC++butistailoredtoprovide,in

manycases,portablecodethatcanbeviewed,modified,and

executedonanymachinewithaVBScripthostorinterpreter.

Unliketheso-calledrealprogramminglanguagesthatmustbe

compiledbeforethesystemcanunderstandthecode,VBScript

remainsinplaintextuntilactualruntimewhenthecodeis

interpretedandexecutedonthesystem.VBScriptcommands

arenotrecognizeddirectlybytheoperatingsystem,sothey

mustberunusingaVBScripthostorinterpreterthatcan

convertthecodesothattheoperatingsystemcanexecutethe

commands.VBScriptisportableanddoesnotcarryalotofthe

overheadthatcansometimesbeassociatedwithcompiled

applicationssuchasDLLfilesandsuch.VBScriptfilescanbe

runusingtheWindowsScriptingHost(WSH)orbewritteninto

aWebpagethatsupportsscripting.

ThefileextensionforaVBScriptfileis.VBS,andthisextension

isconfiguredbydefaulttorunusingWscript.exe.Thisenablesa

VBSfiletobedouble-clickedtorunjustlikeexecutable.EXE

files.Anotheroptionistorunthefilesinacommand-line

environmentusingCscript.exe.



VisualBasicScriptOptions

AVisualBasicscriptisnotcompiledcode,soitmustberun

withinahostorcontextthatcaninterpretthecommandsand

presentthemtotheoperatingsystemsotheyareexecutedas

desired.YoucanmakesureVBScriptcodeisprocessedby



callingthecodeusingtheWindowsScriptingHostoraddingthe

codewithinHTMLorASPWebpagesonWebserversthat

supporttheVBScriptlanguage.Also,beforecompilingthecode,

youcanaddVBScriptcodetoVisualBasicorC-compatible

applicationstohandlecertaintasksorfunctionsthatcanbe

performedwithlesscodethanVBScript.



WindowsScriptingHost

UsingtheWindowsScriptingHost,scriptswritteninVBScriptor

JScriptcanbeinterpretedatruntimeandexecutedonaserver

orworkstation.WSHsupportsrunningscriptsfromthe

commandlineusingCscript.exeandsupportsrunningscripts

withinthegraphicaluserinterfacebyusingWscript.exe.Both

arepartoftheWindowsScriptingHostprogram.Toseethe

differencesandtodiverightintoasimplescript(recommended

inalabenvironment)usingVBScript,followthesesteps:

1. Beforeyoustartcreatingscripts,createadirectorycalled

ScriptsontherootoftheCdrive.

2. ChooseStart,Run.Typenotepad.exeandclickOKtocreateanew

VBScript.Tocreatethescript,typethefollowingcodeinthe

Notepadwindow,pressingEnteraftereachline:

DimCurrentTime

CurrentTime=time

Wscript.echo"Thecurrenttimeis"&CurrentTime&"."

TheDimcommanddeclaresavariablecalledCurrentTimethatcan

bereferencedthroughouttherestofthecode.Thenextlineof

codesetstheCurrentTimevariabletothevalueofthetime

function,whichwillgiveyouthecurrenttime.Thelast

command,Wscript.echo,willdisplaythetextenclosedindouble



quotationmarksfollowedbythevalueoftheCurrentTime

variable.Noticethe&symbolafterthetextandafterthe

variable;itisusedtotelltheWscript.echocommandthatthereis

stillmoreinformationtoechoandtocontinuewritingtothe

sameline.

3. Savethefilewitha.VBSextension,usinganamesuchas

c:\Scripts\VBtime.vbs,andcloseNotepad.

4. ChooseStart,Runandthentypecmd.exetoopenacommand

prompt.

5. Changedirectorytothec:\Scriptsdirectory.

6. TypeWscript.exeVBtime.vbsandpressEnter.Notehowtheoutput

isdisplayedasapop-upwindowwhileWscript.exerunsby

defaultinthegraphicaluserinterface.

7. ClickOKtoclosethepop-upwindowandreturntothe

commandprompt.

8. TypeCscript.exeVBtime.vbsandpressEnter.Notehowtheoutput

isdisplayedinthecommand-lineinterfaceanddoesnotrequire

userinterventiontoacknowledgetheresponsetheway

Wscript.exedoes.



Thereasonthesamecodereturnstheinformationindifferent

waysisinherenttotheWscript.exeandCscript.exe

applications.Theoutputisalsodirectlyrelatedtotheactual

commandsbeingcalled.Forexample,modifytheVBtime.vbs

scriptasfollows,savethefile,andrunthescriptusingboth

Wscript.exeandCscript.exe:

DimCurrentTime

CurrentTime=time



MsgBox"Thecurrenttimeis"&CurrentTime&"."



WhenthisscriptisrunusingeitherWscript.exeorCscript.exe,

theoutputisthesame:apop-upwindowdisplayingthecurrent

time.Thereasonforthisresultisthatthemessagebox(MsgBox)

functionisagraphicfunction,whereastheWscript.echocommand

merelyechoesoutputtothecurrentinterface.



Note

IfacommandsuchasWscript.echoisusedseveral

timesinascript,besuretorunthescriptusing

Cscript.Otherwise,userinterventionwillbe

necessarytocloseeachpop-upwindowsequentially.



ActiveServerPages

ActiveServerPages(ASP)runningonWindowsServer2003

InternetInformationServices(IIS)enableWebdevelopersto

includescriptingcodewithindynamicHTMLpages.Thiscanbe

client-sidescriptingthatisdownloadedandexecutedonthe

enduser'smachineorserver-sidescriptingthatisexecutedon

theback-endserver.Recently,becauseafewproblematic

viruseshavebeenwrittenusingVBScript,manyorganizations

nowdisableclient-sideVBScriptingontheirproxyserversand

firewalls.Insuchcases,client-sidescriptingmaynotfunction

correctly,soserver-sidescriptingshouldbeused.Bydefault

whenaclientchoosestoviewthesourcecode,thescriptwill

notshowup,onlythereturnedvalues.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 23. Automating Tasks Using Windows Server 2003 Scripting

Tải bản đầy đủ ngay(0 tr)

×