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.
DMIT.io是成立于2018年的一家国外主机商,提供VPS主机和独立服务器租用,数据中心包括中国香港、美国洛杉矶和日本等,其中日本VPS是新上的节点,基于KVM架构,国际线路,1Gbps带宽,同时提供月付循环8折优惠码,或者年付一次性5折优惠码,优惠后最低每月8.72美元或者首年65.4美元起,支持使用PayPal或者支付宝等付款方式。下面列出部分日本VPS主机配置信息,价格以月付为例。CPU:...
Hostodo近日发布了美国独立日优惠促销活动,主要推送了四款特价优惠便宜的VPS云服务器产品,基于KVM虚拟架构,NVMe阵列,1Gbps带宽,默认分配一个IPv4+/64 IPv6,采用solusvm管理,赠送收费版DirectAdmin授权,服务有效期内均有效,大致约为7折优惠,独立日活动时间不定,活动机型售罄为止,有需要的朋友可以尝试一下。Hostodo怎么样?Hostodo服务器好不好?...
ZJI发布了一款7月份特别促销独立服务器:香港邦联四型,提供65折优惠码,限量30台(每用户限购1台),优惠后每月520元起。ZJI是原来Wordpress圈知名主机商家:维翔主机,成立于2011年,2018年9月启用新域名ZJI,提供中国香港、台湾、日本、美国独立服务器(自营/数据中心直营)租用及VDS、虚拟主机空间、域名注册等业务。下面列出这款服务器的配置信息。香港邦联四型CPU:2*E5-2...
sendmail为你推荐
快递打印快递单可以自己打印吗51自学网站谁能给我免费学习的网站吧 谢谢了吴晓波频道买粉吴晓波频道学习卡资费?照片转手绘怎么把图片P成手绘arm开发板arm开发板是干什么用的,是用在什么领域方面的正则表达式javajava正则表达式中小企业信息化什么是中小企业信息化途径中小企业信息化中小企业信息化途径有哪些神雕侠侣礼包大全神雕侠侣先手礼包在哪领迅雷云点播账号求一个迅雷云点播vip的账号,只是看的,绝不动任何手脚。
域名邮箱 南通服务器租用 免费顶级域名 骨干网 国外主机 安云加速器 z.com 表格样式 ibrs 本网站在美国维护 骨干网络 毫秒英文 工作站服务器 linux服务器维护 申请免费空间和域名 国外视频网站有哪些 网页提速 国外在线代理服务器 主机返佣 电信宽带测速软件 更多