interactivelysendmail
sendmail 时间:2021-02-23 阅读:(
)
-14-January21,1992DonLibesNationalInstituteofStandardsandTechnologyphotoDonLibesreceivedaB.
A.
inMathematicsfromRutgersUniversityandanM.
S.
inComputerSci-encefromtheUniversityofRochester.
CurrentlyattheNationalInstituteofStandardsandTechnology,DonisengagedinresearchthatwillhelpU.
S.
industrymeasurethestandardhack.
Unfortunately,NISTdoesnothaveaverygoodsenseofhumor,sohewasforcedtowritehisrstbook"LifeWithUNIX"throughPrentice-Hall.
-13-January21,1992expectisdesignedtoworkwithprogramsastheyare.
Programsneednotbechangedorrede-signed,nomatterhowpoorlywritten.
Understandably,themajorityofsystemadministratorsarereluctanttomodifyaprogramthatworksandthattheyhavenotwrittenthemselves.
MostpreferwritingshellscriptsusingtheclassicUNIXtoolsphilosophy.
expecthandlestheseproblems,solvingthemdirectlyandwithelegance.
expectscriptsaresmallandsimpleforproblemsthataresmallandsimple.
Whilenotallexpectscriptsaresmall,thescriptsscalewell.
Theyarecomparableinstyletoshellscripts,beingtask-oriented,andprovidesynergywithshellscripts,bothbecausetheycancallshellscriptsandbecalledbythem.
Usedjudiciously,expectisawelcomenewtooltotheworkbenchofallUNIXsystemadministrators.
AcknowledgmentsThisworkwasjointlyfundedbytheNISTAutomatedManufacturingResearchFacility(AMRF,project734-3385)andScienticandTechnicalResearchServices(STRS,project734-3106).
ThecallbackscriptwaswrittenbyScottPaisley.
WalterRowewrotethesendmailversion-checkingscriptmentionedinthepaper.
ThankstoWalterRoweandKenManheimerfortheirhelpfulcommentsonthispaper.
SueMulroneywashelpfulincorrectingmybadlygrammar.
AvailabilitySincethedesignandimplementationofexpectwaspaidforbytheU.
S.
government,itisinthepublicdomain.
However,theauthorandNISTwouldlikecreditifthisprogram,documentationorportionsofthemareused.
expectmaybeftp'daspub/expect/expect.
shar.
Zfromftp.
cme.
nist.
gov.
expectwillbemailedtoyou,ifyousendthemailmessagesendpub/expect/expect.
shar.
Ztolibrary@cme.
nist.
gov.
References[1]DonLibes,"expect:CuringThoseUncontrollableFitsofInteraction",ProceedingsoftheSummer1990USENIXConference,Anaheim,CA,June10-15,1990.
[2]DonLibes,"TheexpectUserManual–programmaticdialoguewithinteractiveprograms",toappearasaNISTIR,NationalInstituteofStandardsandTechnology,November,1990.
[3]JohnOusterhout,"Tcl:AnEmbeddableCommandLanguage",ProceedingsoftheWinter1990USENIXConference,Washington,D.
C.
,January22-26,1990.
[4]JohnOusterhout,"tcl(3)–overviewoftoolcommandlanguagefacilities",unpublishedmanualpage,UniversityofCaliforniaatBerkeley,January1990.
[5]AT&T,UNIXProgrammer'sManual,Section8.
[6]LarryWall,"Perl–PracticalExtractionandReportLanguage",unpublishedmanualpage,March1990.
-12-January21,1992includesahigh-levellanguagethatisinterpretedandbearsastrongsimilaritytotheshellandalsotoC.
Inthatsense,Iseelittletoargueaboutsinceexpectcandoshell-likefunctions.
Inaprevi-ouspaper[1],Ihavesuggestedtheadditionofexpect'sfeaturestotheshell.
Noonewantstolearnyetanothershell,andthereisnoreasonwhythesecapabilitiescannotbeaddedtotheshell.
PerlAmoreinterestingcomparisoniswithPerl,alanguageclaimed(bytheauthor)[6]toembodythebestaspectsoftheshell,C,awk,sed,andanumberofotherUNIXtools.
HavingspentsometimeprogramminginPerl,thereisnoquestioninmymindthatPerliscapableofsolvingthesametasksthatIhavedescribedinthispaper.
Pseudo-ttypackagesforPerlhavebeenwrittenandsend/expectutilitiescouldbewrittenalso.
Perlisaverypowerfullanguage.
Itismuchricherthanthelanguageusedbyexpect(oranyshellforthatmatter).
Thishasadvantagesanddisadvantages.
ThemostobviousdisadvantageisthatPerl'soverabundanceofoptionsandfeaturessimplyaren'tnecessaryforthetasksthatexpectaddresses.
Perl'scomplexityisreectedinitsdiskspace.
Thecomputeronmydesk,aSun3,requires270KtostorePerlandhasasignicantstartuptime.
expect,ontheotherhand,is70Kwithessentiallynostartuptime.
ThereareotherreasonsthatPerlisnotwidelyappliedtocertainproblems,butcompletingthediscussiondeservesapaperofitsown.
InsteadIwillsummarizebysayingthatexpectisappropriatetoonlyafractionofthesystemadministrationproblemsthatPerlsolves.
Thisisintentionallyso.
expectwaswrittentosolveaveryspecicproblem,anditdoesthatconciselyandefciently.
IthinkthatittswellwiththeUNIXphilosophyofsmalltools,unlikePerlwhichdemandsasignicantinvestmentinmasteringitscomplexity.
Giventhechoice,Ipredictthatmostsystemadministratorswouldchooseatoollikeexpectthattakesverylittleefforttolearn,ratherthanenteringtheworldofPerl.
EmacsEmacsisanalogoustoPerlinmanyways,includingitsexibilityandoverabundanceoffunction-ality.
Similarly,Emacscanbeusedtosolvethesesameproblems.
Andformuchthesamerea-sonsasIgaveabove,EmacsisinappropriatefortheclassofproblemsIhavesuggestedinthispaper.
Indeed,consideringthatEmacshasbeenavailableforoveradecade,andI'veneverheardofanyoneusingitthisway,I'llprofferthatEmacsissoinappropriatefortheseproblems,thatitisnotsurprisingthisusagehasneverevenoccurredtoanyone.
ConclusionUNIXshellsareincapableofcontrollinginteractiveprocesses.
Thishasbeenattherootofmanydifcultiesautomatingsystemadministrationtasks.
WhiletheUNIXcommunityisgraduallyprovidingbetterdesignedtoolsanduserinterfaces,evenmoreprogramsarebeingwrittenwithembarrassinglypooruserinterfacesatthesametime.
Thisisunderstandablebecausesystemadministratorsgivemoreprioritytosolvingaproblemsotheycangotothenextone,thangoingbacktoprettyupanoldandworkingsolution.
-11-January21,1992systems.
HowmuchmoreworkcoulditpossiblybeforyoutoadministerjustonemoresystemOh,anditrunsVMS.
")SecuritySeveraloftheexamplespresentedhavepromptedforpasswordsthataredifferentthantheusualUNIXstyle.
Normally,UNIXpromptsforpasswordsdirectlyfrom/dev/tty.
Thishastheunfor-tunatedrawbackthatyoucannotredirectstdin.
Wehaveshownhowtogetaroundthatbyusingexpect.
Ofcourse,doingthisreopensapossiblesecurityhole.
Unprivilegeduserscandetectpasswordspassedasargumentsbyusingps.
Ifpasswordsarestoredinles,lapsesinsecuritycanmakeplaintextpasswordsevidenttopeoplebrowsingthroughyourles.
Publicly-readablebackupmediaareoneofthesimplestsuchsecuritylapses.
Ifyouareatallinterestedinsecurity,Idonotrecommendstoringplaintextpasswordsinles.
Thelikelihoodofsuchapasswordbeingdiscoveredandabusedisjusttoohigh.
Ourusersstorepasswordsinles,butonlyforhighlyrestrictedaccounts,suchasfordemosoranonymousftp.
Thechancesofleakingapasswordthroughpsarelower,andcanbeloweredfurtherstillbyusingthesmallestpossiblescriptaroundthepasswordpromptingprogram.
Suchawindowisextremelysmall.
Nonetheless,securesitesshouldnottakeeventhischance.
Analternativeistohaveexpectinteractivelypromptforpasswords.
Ifyouhaveanexpectscriptthatisdoingacomplicatedseriesoftelnets,ftpsandotherthings,thescriptscanencodeevery-thingbutthepasswords.
Uponrunningsuchascript,theuserwillbeonlybepromptedonceforapassword,andnothingelse.
Thenexpectwillusethatpasswordwhenevernecessary,andcom-pletealltheotherdialoguefromdatapre-storedinles.
Insummary,expectneednotweakensecurity.
Usedwisely,expectcanevenenhancesecurity.
However,youmustusecommonsensewhenwritingscripts.
ComparisontoothersystemadministrationtoolsThissectionofthepapercanbeconsideredcontroversyorheresy,asyouwish.
Itissomewhatreligiousinthattheargumentscanonlyberesolvedbyphilosophicalchoiceratherthanlogic.
IhavekeptitdowntoaveryfewreasonstogiveyouonlythebarestfeelingsforwhatIconsiderisimportanttounderstandwhenchoosingexpectoverothersystemadministrationtools.
Asshouldbeobvious,Ithinkthereareveryfewalternativestousingexpect.
Traditionally,thepopularchoiceshavebeen1)avoidanceand2)Cprogramming.
Thesearenownolongertheonlychoices.
ShellTheshellisincapableofcontrollinginteractiveprocessesinthewaythatexpectcan.
Nonethe-less,certaincomparisonsbetweenexpectandtheshellareinevitable.
Inparticular,expect-10-January21,1992youcantransferahierarchynomatterwhatitlookslikeorhowdeepitis.
expectsupportsrecur-siveprocedures,makingthistaskashortscript.
Mysiteregularlyretrieveslargedistributions(e.
g.
,Gnu,X)thisway.
Assistingadbandother"dumb"programsQuiteoften,vendorsprovideinstructionsformodifyingsystemsintheformofadbinstructions,wheresomeinstructionsmaydependontheresultsofearlierones(i.
e.
,"eachtime_maxusersisincremented,youmustadd16to_nle").
adbhasnospecialscriptinglanguagethatsupportssuchinteraction,nordoestheshellprovidethiscapability.
expectcanperformthisinteraction,playingthepartoftheuser,bydirectlylookingattheresultsofoperations,justasauserwould.
Thistechniquecanbeappliedtoanyprogram.
Infact,expectcanactasanintermediarybetweentheuserandprogramswithpoorly-writtenuserinterfaces.
expectnormallyshowstheentiredia-loguebutcanbetoldnotto.
Thenexpectcanprompttheuserforcommandssuchasshow_maxusersinsteadofadb'snativebutcryptic_maxusers/d.
Translationscanalsobeper-formedinthereversedirection.
Ashortexpectscriptcouldlimitthedifcultyofsystemadminis-tratorswhohavenointerestinmasteringadb.
Inaddition,theabilityofsystemadministratorstoaccidentallycrashthesystembyafewerrantkeystrokeswouldbedramaticallylessened.
GreppingmonsterloglesAcommoncommandsequenceinvolveslookingatalogwith,say,grep,andtheninterruptingit(with^C)afterthelineofinterestappears.
Unfortunately,grepandotherprogramsarelimitedtotheamountofprogrammabilitytheyhave.
Forexample,grepcannotbedirectedtostopsearch-ingaftertherstmatch.
Ashortexpectscriptcansendaninterrupttogrepafterseeingtherstlinejustasiftheuserwereactuallyatthekeyboard.
Withprogramsthatgenerateloglesaslargeasagigabyte,thisisarealproblem.
Withoutexpect,theonlysolutionsaretoletgrepcontinuerunningoverthewholele,ortodedicateahumantothetaskofpressing^Cattherighttime.
expectcancutofftheprocessassoonaspos-sible,mailingtheresultsbackthesystemadministratorifnecessary.
Ingeneral,expectisusefulforsendingoddcharacterstoaprocessthatcannotbeembeddedinashellscript.
expectcanalsoexecutejobcontrolcommands(bg,fg,etc.
)inordertomediatebetweenprocessesthatwereneverdesignedtocommunicatewitheachother.
Again,thiscanrelieveahumanfromthetedioustaskofinteractivelymonitoringprograms.
Administeringnon-UNIXsystemsexpectisaUNIXprogram,yetitcanbeusedtoadministernon-UNIXsystems.
Howisthispos-sibleRunningtelnet(tip,kermit,etc.
)toanon-UNIXhost,itcanloginandperformsend/ex-pectsequencesontheremotecomputer.
Theoperatingsystemorenvironmentoftheremotecomputeriscompletelyirrelevanttoexpect,sinceallofthisisisolatedtotheexpectscriptitself.
ThisisveryusefulforsystemadministratorsthatalreadyhaveaUNIXcomputerontheirdeskbutareforcedbymanagementtoadministeranothercomputer.
("Youalreadyadminister20UNIX-9-January21,1992su,passwd,cryptandotherpassword–eatersProgramsthatreadandwrite/dev/ttycannotbeusedfromshellscriptswithouttheshellscriptaccessing/dev/tty.
Anearlierexampleshowedhowtoforcepasswdnottoreadfrom/dev/tty.
Withthistechnique,youcanchangeitsinputsourcetostdin,aparameter,orevenanenvironmentvariable.
Asanotherexample,supposeyouhavetypedacommandthatfailsbecauseyouweren'troot.
Thetypicalreactionistotypesuandthenreenterthecommand.
Unfortunately,historywon'tworkinthissituationas!
-2willjustevoketheerror-1:Eventnotfound.
Theproblemisthatyouwanttorefertoacommandthatisnowinadifferentshellinstantiation,andthereisnowaytogetbacktoit.
Asolutionistopassthefailedcommandasanargument(via!
!
)toanexpectscriptthatwillpromptyoufortherootpassword,invokesu,andthenfeedtheoriginalfailedcommandtotheresultingsuperusershell.
Iftheexpectscriptexecutesinteractasitslastaction,youwillhavetheoriginalcommandexecutedforyou(noretyping),plusyouwillgetanewsuperusershell.
Thereisnowaytodothiswithsuexceptbyresortingtotemporarylesforyourhistoryandalotofretyping.
Amorepainfulexampleisnewgrp.
Unlikesu,newgrpdoesnotallowadditionalargumentsonthecommandlinetobepassedtothenewshell.
Youmustinteractivelyenterthemafternewgrpbeginsexecuting.
Ineithercase,bothsuandnewgrpareessentiallyuselessinshellscripts.
Security–Thegoodnewsis…Earlier,Imentionedhowtobuildascriptthatwouldforceuserstochoosegoodpasswordswith-outrewritingpasswd.
Allotheralternativeseitherrewritethepasswdprogramorasktheusertoberesponsibleforchoosingagoodpassword.
Ontheoppositesideofthecoin,expectcanbeusedtotestothersitesforsecurelogins(ortobreakin,Isuppose).
Tryingtologinasrootusing,say,allthewordsinanon-linedictionary,atallthelocalhostsatasitewouldbeprohibitivelyexpensiveforahumantodo.
expectwouldworkatitrelentlessly,eventuallyndinganinsecureroot,orshowingthesitetobeprotectedbygoodpasswords.
QuestionsatboottimeWhilebooting,itisusefultovalidateimportantsystemfacts(e.
g.
,date)beforecomingupalltheway.
Ofcourse,ifnooneisstandinginfrontoftheconsole(e.
g.
,thesystembootedduetoapowerfailure)thecomputershouldcomeupanyway.
Writingsuchascriptusingtheshellispain-ful,primarilybecausearead-with-timeoutisnotdirectlyimplementedintheshell.
Inexpect,allreadstimeout.
expectcanpromptandreadfromthekeyboardjustaseasilyasfromaprocess.
TransferringhierarchieswithftpAnonymousftpisverypainfulwhenitcomestodirectoryhierarchies.
Sincethereisnorecursivecopycommand,youmustexplicitlydocdsandgets.
Youcanautomatethisinashellscript,butonlyifthehierarchyisknowninadvance.
expectcanexecuteanlsandlookattheresultssothat-8-January21,1992Inthissection,moreexampleswillbediscussed.
Becauseofspacelimitations,scriptswillnotbeshown,butallofthemhavebeenwrittenandarebeingused.
RegressiontestingTestingnewreleasesofinteractivesoftware(tip,telnet,etc.
)requiresahumantopresskeysandwatchforcorrectresponses.
Doingthismorethanafewtimesbecomesquitetiresome.
Natu-rally,peoplearemuchlesslikelytorunthoroughregressiontestsaftermakingsmallchangesthattheythinkprobablydon'taffectotherpartsofaprogram.
Regressiontestingcanalsobeusefulforyourentireinstallation.
Youcanmakeascriptthattestsallyoursite'slocalapplications,andrunitataftereachsystemupgradeorcongurationchange.
AutomatingloginsManyprogramshaveafrequentlyrepeated,well-denedsetofcommandsandanothersetthatarenotwell-dened.
Forexample,atypicaltelnetsessionalwaysbeginswithalogin,afterwhichtheusercandoanything.
Toautomatethis,expecthastheabilitytopasscontrolfromthescripttotheuser.
Atanytime,theusercanreturncontroltothescripttemporarilytoexecutesequencesofcommonlyrepeatedcommands.
Atmysite,expectisheavilyusedtoautomatetheprocessoflogginginthroughmultiplefront-endsandcommunicationswitches.
Infact,theoriginalreasonexpectwaswrittenwastocreatesixwindows,eachofwhichautomaticallyloggedintoanotherhosttorunademo.
Thegeneralideaofautomatingtelnet,ftp,andtipisveryusefulwhendealingwithhoststhatdonotsupportrloginandrcp.
ButthetechniqueisalsousefulwithnativeUNIXcommandslikesu,login,orrlogin.
expectscriptscancallanyofthem,sendingpasswordsasappropriateandthencontinuingactionsasdesired.
Whileanyofthesecommandscanbeembeddedinashellscript,theshellhasnowayoftakingcontroloverwhathappensinsideoftheseprograms.
Subsequentcommandsfromtheshellscriptdonotgetsenttothenewcontext,butareheldupuntiltheprevi-ouscommandhascompletedsothattheycanbesenttotheoriginalcontext.
expecthasnosuchproblemsswitchingcontextstocontinuecontrollinganyofthesesessions.
telnet–It'snotjustforbreakfastanymoretelnetalsofunctionsasaninterfacetotheexcitingworldofTCPsockets.
telnetcanbeusedtoaccessnon-telnetsocketsandqueryotherhostsfortheirdate(port13),time(port37),listofactiveusers(port11),userinformation(port43),networkstatus(port15),andallsortsofothergoodiesthatyoumightonlybeabletogetifyouhadpermissiontologin.
Forexample,oursiteregularlyrunsascriptthatchecks(port25)whatversionofsendmail.
cfeachofourlocalhostsisactuallyusing.
Ifwedidthisbyreadingles,wewouldneedpermissiontologin,orremotelymountlesystemsandreaddirectoriesandlesonseveralhundredhosts.
Usingtelnetismucheasier,albeitalittlestrange.
-7-January21,1992isimportantisthatexpectscriptsaresmallandsimpleforproblemsthataresmallandsimple.
expectobviatestheneedforresortingtoCjustbecauseoflimitationsonthepartoftheshell.
Example–IntelligentftpOneofoursiteadministratorswantedtospoollesinadirectory.
Later,asecondcomputerwoulduseftptopickthemupandthendeletethemfromtherstcomputer.
Hisrstattemptwastousemget*followedbymdelete*.
Unfortunately,thisdeleteslesthatarriveinthewin-dowbetweenwhenthemgetstartsandthemdeletestarts.
ThescriptfragmentinListing5solvedtheproblem.
Thescriptbeginsbyspawningftp.
Ihaveomittedseverallinesthatopenaconnectionfollowedbysendingandconrmingtheuserandpasswordinformation.
Thenextlinesendsanftpcom-mandtostorethelistofremotelesinalocallecalledlsFile.
Thiscommandisterminatedbyasemicolon,allowingtheresponsetobeveriedwithanexpectcommandonthesamelineofthescript.
exec–ExecuteaUNIXcommand.
execexecutesaUNIXcommandandsimplywaitsforittocomplete,justasifitwereinashellscript.
Inlinefour,catreturnsthelistofles,andtheirnamesarestoredinthevariable,lsVar.
execisusedagaininthenextline,thistimetodeletethelocalle,lsFile.
TheremainderofthescriptmerelyiteratesthroughthevariablelsVar,sendinggetcommandsfol-lowedbydeletecommandsforeachlefoundintheearlierls.
Otherexamplessolvedexpectaddressesasurprisinglylargeclassofsystemadministrationproblemswhichbeforenowhaveeitherbeensolvedbyavoidanceorspecialkludges.
Atthesametime,expectdoesnotattempttosubsumefunctionsalreadyhandledbyotherutilities.
Forexample,thereisnobuilt-inletransfercapability,becauseexpectcanjustcallaprogramtodothat.
Andwhiletheshellisprogrammable,itcannotinteractwithotherinteractiveprocessesanditcannotsolveanyoftheexamplesinthispaper.
Listing5Fragmentofftpspoolscript.
spawnftp.
.
.
sendls*lsFile\r;expect*success*ftp>*setlsVar[execcatlsFile]execrmlsFile\rsetlen[length$lsVar]for{seti0}{$i*senddelete$file\r;expect*success*ftp>*}-6-January21,1992Ifthescriptdoesnotmatchoneoftheprespeciedanswers,thelastcasematches.
(Theisnecessarytopreventthescriptfromtriggeringbeforetheentirequestionarrives.
)Theinteractactionpassescontrolfromthescripttothekeyboard(actuallystdin)sothatahumancananswerthequestion.
interact–Passcontrolfromscripttouserandback.
Duringinteract,theusertakescontrolfordirectinteractions.
Controlisreturnedtothescriptafterpressingtheoptionalescapecharacter.
Inthisscript,+ischosenastheescapecharacterbypassingitastheargumenttointeract.
Arealexpectscriptforfsckwoulddoseveralotherthings.
Forexample,fsckusesseveralstati-cally-sizedtables.
Forthisreason,fsckislimitedtothenumberoferrorsofonetypethatcanbexedinasinglepass.
Thismayrequirefsckberunseveraltimes.
Whilethemanualsaysthis,fsckdoesn't,andfewsystemadministratorsknowfsckthatintimately.
Whenrunfromashellscript,thislackofprogrammabilitywillcausethesystemtocomeupallthewaywithacorruptlesystem(ifthereturncodeisn'tchecked)orbeunnecessarilyrebootedseveraltimes(ifthereturncodeischecked).
Example–CallbackThescriptinListing4waswrittenbyauserwhowantedtodialupthecomputer,andtellittocallhimback.
Sincehelivedoutofthelocalcallingarea,thiswouldgetthecomputertopickuphislong-distancephonebillsforhim.
Therstlinespawnstipwhichopensaconnectiontoamodem.
Next,expectwaitsfortiptosayitisconnectedtothemodem.
Theuser'sphonenumber,passedastherstargumenttothescript,isthenfetchedandaddedtoacommandtodialaHayes-compatiblemodem.
Acarriage-returnisappendedtomakeitappearasifauserhadtypedthestring,andthemodembeginsdialing.
Thethirdlineassigns60tothevariabletimeout.
expectactuallylooksatthisvariableinordertotellithowmanysecondstowaitbeforegivingup.
Eventuallythephoneringsandthemodemanswers.
expectndswhatit'slookingforandexits.
Atthispointgettywakesup,andndingthatithasadialuplinewithDTRonit,startsloginwhichpromptstheusertologin.
Sincethescriptwasoriginallywritten,wehaveaddedafewmorelinestoautomateandverifyphonenumbersbasedontheuidrunningitpartlyforsecurity,butthefragmentshownherewasusedsuccessfullyandformstheheartofourcurrentscript.
Ironically,werecentlynoticeda60KbequivalenttocallbackonUsenetthathadnomorefunctionalitythanadozenorsolinesofexpect.
Ofcourse,notallscriptsarethisshort.
I'mlimitedtowhatcanbepresentedhere,andtheseexamplesreallyservejusttogiveyouafeelofwhatexpectdoesandhowitcanbeapplied.
WhatListing4Callbackscript.
Firstargumentisphonenumber.
spawntipmodemexpect{*connected*}sendATDT[index$argv1]\rsettimeout60expect{*CONNECT*}-5-January21,1992"Assumeayesresponsetoallquestionsaskedbyfsck;thisshouldbeusedwithextremecaution,asitisafreelicensetocontinue,evenaftersevereproblemsareencountered.
"The-noptionhasasimilarlyworthlessmeaning.
Thiskindofinterfaceisinexcusablybad,andyetmanyprogramshavethesamestyle.
Forexample,ftphasanoptionthatdisablesinteractivepromptingsothatitcanberunfromascript,butitprovidesnowaytotakealternativeactionshouldanerroroccur.
Usingexpect,youcanwriteascriptthatallowsfscktoberun,havingquestionsansweredauto-matically.
Listing2isascriptthatcanrunfsckunattendedwhileprovidingthesameexibilityasbeingruninteractively.
Thescriptbeginsbyspawningfsck.
for–Controlsiteration(looping).
Thelanguageusedbyexpectsupportscommonhigh-levelcontrolstructuressuchasif/then/else.
Inthesecondline,aforloopisusedwhichisstructuredsimilarlytotheC-languageversion.
Thebodyoftheforcontainsoneexpectcommand.
Thefollowingexpectcommanddemonstratestheabilitytolookformultiplepatternssimulta-neously.
(Thebackslashes(\)areusedtoquotecharacters–inthiscasewhitespace.
)Inaddition,eachpatterncanhaveanaccompanyingactiontoexecuteifthepatternisfound.
Thisallowsustoprespecifyanswersforspecicquestions.
WhenthequestionsUNREFFILE…CLEARorBADINODENUMBER…FIXappear,thescriptwillautomaticallyanswery.
Ifanythingelseappears,thescriptwillanswern.
Ingeneral,ifallquestionsareknownandanswerableinadvance,ascriptcanberunintheback-ground.
Withmorecomplexprogramsitmaybedesirabletotrapunexpectedquestionsandforceausertointeractivelyevaluatethem.
Listing3isascriptdoesexactlythis.
Listing2Non-interactivefsckscript.
spawnfsckfor{}1{}{expecteofbreak\{*UNREF\FILE*CLEAR\}{sendy\r}\{*BAD\INODE*FIX\}{sendy\r}\{*\}{sendn\r}}Listing3User-friendlyfsckscript.
spawnfsckfor{}1{}{expecteofbreak\{*UNREF\FILE*CLEAR\}{sendn\r}\{*BLK(S)\MISSING*SALVAGE\}{sendy\r}\{*\}{interact+}}-4-January21,1992spawn–Runsaninteractiveprogram.
Thespawnedprogramisreferredtoasthecurrentprocess.
Inthisexample,passwdisspawnedandbecomesthecurrentprocess.
Ausernameispassedasanargumenttopasswd.
expect–Looksforapatternintheoutputofthecurrentprocess.
Theargumentdenesthepattern.
Additionaloptionalargumentsprovidealternativepatternsandactionstoexecutewhenapatternisseen.
(Anexamplewillbeshownlater.
)Inthisexample,expectlooksforthepatternpassword.
Theasteriskallowsittomatchotherdataintheinput,andisausefulshortcuttoavoidspecifyingeverythingindetail.
Thereisnoactionspecied,sothecommandjustwaitsuntilthepatternisfoundbeforecontinuing.
send–Sendsitsargumentstothecurrentprocess.
Thepasswordissenttothecurrentprocess.
The\rindicatesacarriage-return.
(Allthe"usual"Cconventionsaresupported.
)Therearetwosend/expectsequencesbecausepasswdasksthepasswordtobetypedtwiceasaspellingverication.
Thereisnopointtothisinanon-interactivepasswd,butthescripthastodothisbecausepasswddoesn'tknowbetter.
Thenalexpecteofsearchesforanend-of-leintheoutputofpasswdanddemonstratestheuseofkeywordpatterns.
Anotheroneistimeout,usedtodenotethefailureofanypatterntomatch.
Here,eofisnecessaryonlybecausepasswdiscarefullywrittentocheckthatallofitsI/Osucceeds,includingthenalnewlineproducedafterthepasswordhasbeenenteredasecondtime.
Itiseasytoaddacallandtestofgrep$password/usr/dict/wordstothescripttocheckthatapassworddoesn'tappearintheon-linedictionary,however,wewillleavetheillustra-tionofcontrolstructurestothenextexample.
Example–fsckManyprogramsareostensiblynon-interactive.
Thisis,theycanruninthebackgroundbutwithaveryreducedfunctionality.
Forexample,fsckcanberunfromashellscriptonlywiththe-yor-noptions.
Themanual[5]denesthe-yoptionasfollows:Listing1Non-interactivepasswdscript.
Firstargumentisusername.
Secondargumentisnewpassword.
setpassword[index$argv2]spawnpasswd[index$argv1]expect{*password:}send$password\rexpect{*password:}send$password\rexpecteof-3-January21,1992expectisageneral-purposesystemforsolvingtheinteractiveprogramproblem,howeveritsolvesanunusuallylargenumberofproblemsinthesystemadministrationarena.
WhiletheUNIXstyleistobuildsmallprogramsthatcanbeusedasbuildingblocksintheconstructionofotherpro-gramsusingshellsandpipelines,fewsystemadministrationprogramsbehavethisway.
Traditionally,littletimewasspentdesigninggooduserinterfacesforsystemadministratortools.
Thereasonsmaybeanyorallofthefollowing:Systemadministratorswereexperiencedprogrammers,andthereforedidn'tneedallthehand-holdingthatgeneraluserprogramsrequire.
Programssuchasfsckandcrashwereruninfrequently,sotherewaslittlepointspendingmuchtimeonsuchrarelyusedtools.
Systemadministrationtoolswereusedinextremeconditions,considerednotworthprogrammingforbecauseoftheirdifcultyorrarity.
Itwasmorecost-effectivetosolvetheproblembyhandinreal-time.
Systemadministratorssolvedproblemsinsite-dependentways,neverexpect-ingtheirunderdesignedprogramstobepropagatedwidely.
Whateverthereason,theresultisthattheUNIXsystemadministrator'stoolboxislledwithrep-resentativesofsomeoftheworstuserinterfaceseverseen.
Whileonlyacompleteredesignwillhelpalloftheseproblems,expectcanbeusedtoaddressagreatmanyofthem.
Example–passwdTheexpectscriptinListing1takesapasswordasanargument,andcanberunnon-interactivelysuchasbyashellscript.
Ashellscriptcouldpromptandrejecteasilyguessedpasswords.
Alter-natively,theshellscriptcouldcallapasswordgenerator.
Suchacombinationcouldcreatelargenumbersofaccountsatatimewithoutthesystemadministratorhavingtohand-enterpasswordsasiscurrentlydone.
Admittedly,thescriptreopenstheoriginalsecurityproblemthatpasswdwasdesignedtosolve.
Thiscanbeclosedinanumberofways.
Forexample,expectcouldgeneratethepasswordsitselfbydirectlycallingthepasswordgeneratorfromwithinthescript.
ThescriptinglanguageofexpectisdenedcompletelybyLibes[1][2]andOusterhout[3][4].
Inthispaper,commandswillbedescribedastheyareencountered.
Ratherthangivingcomprehen-siveexplanationsofeachcommand,onlyenoughtounderstandtheexampleswillbesupplied.
set–Setstherstargumenttothesecond(i.
e.
,assignment).
Inline1ofthescript,therstargumenttosetispassword.
Thesecondisanexpressionthatisevaluatedtoreturnthesecondargumentofthescriptbyusingtheindexcommand.
Therstargu-mentofindexisalist,fromwhichitretrievestheelementcorrespondingtothepositionofthesecondargument.
argvreferstotheargumentsofthescript,inthesamestyleastheClanguageargv.
-2-January21,1992IntroductionUNIXsystemadministrationofteninvolvesusingprogramsdesignedforinteractiveuse.
Manysuchprograms(passwd,su,etc.
)cannotbeplacedintoshellscripts.
Someprograms(fsck,dump,etc.
)arenotspecicallyinteractive,buthavelittlesupportforautomateduse.
Forexamplethepasswdcommandpromptstheuserforapassword.
Thereisnowaytosupplythepasswordonthecommandline.
Ifyouusepasswdfromashellscript,itwillblockthescriptfromrunningwhileitpromptstheuserwhoinvokedtheshellscript.
Becauseofthis,youcannot,forexample,rejectpasswordsthatarefoundinthesystemdictionary,acommonsecuritymeasure.
Itisironicthatsecuritywasthereasonthatpasswdwasdesignedtoreaddirectlyfromthekeyboardtobeginwith.
passwdisnotaloneinthisrecalcitrantbehavior.
Manyotherprogramsdonotworkwellinsideofshellscriptsandquiteafewofthesearecrucialtoolstothesystemadministrator.
Examplesarerlogin,telnet,crypt,su,dump,adb,andfsck.
Moreproblemswillbementionedlater.
Theproblemwithalloftheseprogramsisnottheprogramsthemselves,buttheshell.
Forexam-ple,theshellcannotseepromptsfrominteractiveprogramsnorcanitseeerrormessages.
Theshellcannotdealwithinteractiveprogramsthiswaybecauseitisincapableofcreatingatwo-wayconnectiontoaprocess.
ThisisaninherentlimitationofclassicUNIXshellssuchassh,cshandksh(fromhereongenericallyreferredtoassimplytheshell).
expect–AnOverviewexpectisaprogramthatsolvesthegeneralproblemofautomatinginteractiveprograms.
expectcommunicateswithprocessesbyinterposingitselfbetweenprocesses(seeFigure1).
Pseudo-ttysareusedsothatprocessesbelievetheyaretalkingtoarealuser.
Ahigh-levelscriptenableshan-dlingofvariedbehavior.
Thescriptoffersjobcontrolsothatmultipleprogramscanbecontrolledsimultaneouslyandaffectoneanother.
Also,arealusermaytakeandreturncontrolfromandtothescriptwhenevernecessary.
Figure1.
expectiscommunicatingwith5processessimultaneously.
Thescriptisincontrolandhasdisabledloggingtotheuser.
Theuseronlyseeswhatthescriptsaystosendandisessentiallytreatedasjustanotherprocess.
expectinteractiveprocessesscriptJanuary21,1992UsingexpecttoAutomateSystemAdministrationTasksDonLibesNationalInstituteofStandardsandTechnologyMetrologyBldg,RoomA-127Gaithersburg,MD20899libes@cme.
nist.
govABSTRACTUNIXsystemadministrationofteninvolvesprogramsdesignedonlyforinteractiveuse.
Manysuchprograms(passwd,su,etc.
)cannotbeplacedintoshellscripts.
Someprograms(fsck,dump,etc.
)arenotspecificallyinteractive,buthavepoorsupportforautomateduse.
expectisaprogramwhichcan"talk"tointeractiveprograms.
Ascriptisusedtoguidethedialogue.
Scriptsarewritteninahigh-levellanguageandprovideflexi-bilityforarbitrarilycomplexdialogues.
Bywritinganexpectscript,onecanruninteractiveprogramsnon-interactively.
Shellscriptsareincapableofmanagingthesesystemadministrationtasks,butexpectscriptscancontrolthemandmanyothers.
Tasksrequiringapersondedi-catedtointeractivelyrespondingtobadlywrittenprograms,canbeautomated.
Inalargeenvironment,thetimeandaggravationsavedisimmense.
expectissimilarinstyletotheshell,andcaneasilybemasteredbyanysystemadministratorwhocanprogramintheshellalready.
Thispaperpresentsrealexam-plesofusingexpecttoautomatesystemadministrationtaskssuchaspasswdandfsck.
Alsodiscussedareanumberofothersystemadministrationtasksthatcanbeautomated.
Keywords:expect,fsck,interaction,passwd,password,programmeddialogue,security,shell,Tcl,UNIX,uucpReprintedfromProceedingsoftheFourthUSENIXLISALargeInstallationSys-temsAdministration(LISA)Conference,ColoradoSprings,CO,October17-19,1990.
Webhosting24宣布自7月1日起开始对日本机房的VPS进行NVMe和流量大升级,几乎是翻倍了硬盘和流量,价格依旧不变。目前来看,日本VPS国内过去走的是NTT直连,服务器托管机房应该是CDN77*(也就是datapacket.com),加上高性能平台(AMD Ryzen 9 3900X+NVMe),还是有相当大的性价比的。此外在6月30日,又新增了洛杉矶机房,CPU为AMD Ryzen 9...
易探云怎么样?易探云香港云服务器比较有优势,他家香港BGP+CN2口碑不错,速度也很稳定。尤其是今年他们动作很大,推出的香港云服务器有4个可用区价格低至18元起,试用过一个月的用户基本会续费,如果年付的话还可以享受8.5折或秒杀价格。今天,云服务器网(yuntue.com)小编推荐一下易探云国内云服务器优惠活动,北京和深圳这二个机房的云服务器2核2G5M带宽低至330.66元/年,还有高配云服务器...
wordpress外贸集团企业主题,wordpress通用跨屏外贸企业响应式布局设计,内置更完善的外贸企业网站优化推广功能,完善的企业产品营销展示 + 高效后台自定义设置。wordpress高级推广外贸主题,采用标准的HTML5+CSS3语言开发,兼容当下的各种主流浏览器,根据用户行为以及设备环境(系统平台、屏幕尺寸、屏幕定向等)进行自适应显示; 完美实现一套主题程序支持全部终端设备,保证网站在各...
sendmail为你推荐
快递打印快递单可以自己打印吗照片转手绘如何把真人图片用photoshop做成手绘图片正则表达式javajava正则表达式腾讯文章怎样才能在手机腾讯网上发表文章?机械键盘轴打游戏用机械键盘到底什么轴好?安全漏洞如何发现系统安全漏洞gbk编码表GB GBK utf8码的区别三星s8什么时候上市三星盖乐世S8上市时间公布 三星盖乐世s8多少钱微信电话本怎么用微信电话本在哪里 微信电话本怎么打开手工杀毒手工杀毒与杀毒软件杀毒有什么区别?
美国虚拟主机购买 哈尔滨域名注册 中国万网域名 naning9韩国官网 重庆服务器托管 l5520 koss 网络星期一 英语简历模板word lighttpd web服务器的架设 韩国名字大全 可外链网盘 1g空间 福建铁通 能外链的相册 网页提速 starry 攻击服务器 域名和主机 更多