Generatore di script Expect
Scegli ssh, telnet o un altro programma, il modo di accesso, un profilo di dispositivo (Cisco IOS XE, F5 BIG-IP tmsh, FortiOS, Extreme Switch Engine e Fabric Engine, oppure un prompt tuo) e i comandi, e ottieni uno script Expect completo che accede, gestisce la paginazione, esegue i comandi ed esce, senza modificare nulla sul dispositivo a meno che tu non lo chieda (su FortiOS risponde a --More-- invece di cambiare un’impostazione globale). Nello script non viene mai scritta nessuna password, nulla di segreto finisce in un log, ssh verifica le chiavi host con accept-new, e ogni script generato supera l’analizzatore di script Expect senza errori né avvisi.
Testo e utilitàConservato in questo browser · La mia scrivania
Lo script legge la password dall’ambiente, verifica che ci sia e la rimuove dall’ambiente prima di avviare ssh, telnet o il programma.
Prompt, paginazione ed enable da Cisco IOS XE 17.x System Management Configuration Guide; Cisco IOS Configuration Fundamentals Command Reference (IOS and IOS XE), consultati il 2026-10-27. Expect against network devices
#!/usr/bin/expect -f
# Written by the Expect script builder (ronutz.com/tools/expect-script-builder).
# Logs in to Cisco IOS XE (the IOS command line) over ssh, runs 2 commands and logs out.
# Device profile: cisco-ios, from the vendor's documents read on 2026-10-27.
# Run it with: expect <this file>
# It reads DEVICE_PASSWORD from the environment; nothing secret is written in this file.
# Exit status: 0 done; 1 the login failed; 2 missing or wrong input; 3 a command did not finish; 4 the session closed early.
# Wait up to 30 seconds for each step of the login.
set timeout 30
# The device.
set host "sw1.example.net"
# The account.
set user "netops"
# The password comes from the environment variable DEVICE_PASSWORD, never from this file.
if {![info exists env(DEVICE_PASSWORD)] || $env(DEVICE_PASSWORD) eq ""} {
send_user "Set DEVICE_PASSWORD in the environment first.\n"
exit 2
}
set password $env(DEVICE_PASSWORD)
# Take it out of the environment, so the programs this script starts do not inherit it.
unset env(DEVICE_PASSWORD)
# Keep the login off the screen, so nothing a device echoes there can be seen.
log_user 0
# Connect. accept-new records the key of a host met for the first time and refuses a host whose key has changed.
spawn ssh -o StrictHostKeyChecking=accept-new -l $user $host
# Log in: answer the password question once, then wait for the prompt.
set login_tries 0
expect {
-nocase -re {password: ?$} {
if {$login_tries > 0} {
send_user "The password was refused.\n"
exit 1
}
incr login_tries
send -- "$password\r"
exp_continue
}
-re {(?:^|[\r\n])[^\r\n#>]+[>#] ?$} { }
timeout {
send_user "No prompt from $host within $timeout seconds.\n"
exit 1
}
eof {
send_user "The connection to $host closed before the prompt: the login was refused, the host key has changed, or the host cannot be reached.\n"
exit 1
}
}
# Send one command line, then wait for the prompt that follows its output.
# Each line of output restarts the timer, so the timeout counts silence, not the whole command.
proc run_command {command} {
global host timeout
send -- "$command\r"
expect {
-re {(?:^|[\r\n])[^\r\n#>]+[>#] ?$} { }
-re {[\r\n]} { exp_continue }
timeout {
send_user "\n\"$command\" did not finish: nothing more came from $host for $timeout seconds.\n"
exit 3
}
eof {
send_user "\n$host closed the session during \"$command\".\n"
exit 4
}
}
}
# From here on, each command may stay silent for up to 60 seconds.
set timeout 60
# Turn paging off for this session.
run_command "terminal length 0"
# Show the session from here on.
log_user 1
# The commands.
run_command "show version"
run_command "show ip interface brief"
# Log out, and wait for the device to close the connection.
send -- "exit\r"
expect {
eof { }
timeout {
send_user "$host did not close the session; closing it.\n"
close
}
}
wait
exit 0
L’analizzatore di script Expect lo legge qui: 0 errori, 0 avvisi, 0 note. Apri l’analizzatore
- Imposta DEVICE_PASSWORD nell’ambiente della shell che esegue lo script; lo script la verifica e la rimuove dall’ambiente prima di avviare la connessione.
expect login-and-run.exp Imposta prima DEVICE_PASSWORD.
0completato1l’accesso non è riuscito (nessun prompt in tempo, connessione chiusa o password rifiutata)2input mancante o errato (una variabile non impostata, un argomento host non valido, nessuna password inserita)3un comando non è terminato (silenzio più lungo del timeout del comando, una domanda a cui nessuno ha risposto)4la sessione si è chiusa mentre era in esecuzione un comando o enable
- Che cosa fa lo script, come eseguirlo, da dove provengono i suoi segreti e i suoi stati di uscita.
- Il timeout di ogni fase di accesso, impostato prima del primo expect, così nessun expect viene eseguito con il valore predefinito di 10 secondi.
- L’host (fisso, oppure preso dalla riga di comando e verificato) e l’utente.
- La password dall’ambiente: presente e non vuota, altrimenti lo script si interrompe; poi rimossa dall’ambiente, così nessun programma avviato dallo script la eredita.
- log_user 0: l’accesso resta fuori dallo schermo, quindi nulla di ciò che un dispositivo vi rimanda in eco può essere visto.
- La connessione: ssh con StrictHostKeyChecking=accept-new (e BatchMode con una chiave), telnet o il programma.
- Un solo expect per tutto l’accesso: a ogni domanda si risponde una volta (una seconda richiesta significa che è stata rifiutata), il prompt lo conclude, e timeout ed eof interrompono lo script con stato 1.
- run_command: invia una riga con un invio a capo, poi attende il prompt; ogni riga di output fa ripartire il timer (exp_continue), quindi il timeout misura il silenzio.
- Il timeout di ogni comando, al livello principale, dopo l’accesso.
- I comandi del profilo che disattivano la paginazione, ciascuno atteso come qualsiasi comando.
- Da qui in poi la sessione va sullo schermo, nel file di log o in entrambi; il file viene aperto solo ora.
- I tuoi comandi, ciascuno inviato così come è scritto (con i caratteri speciali di Tcl protetti).
- Il comando di disconnessione e la fine della connessione (o un close), poi wait, così il processo viene raccolto.
Il generatore scrive lo script nel tuo browser e non lo esegue mai. Non risponde alle domande poste da un comando, non gestisce un prompt che sfugge al pattern del profilo (ad esempio un banner o una riga di comando che termina con > o #), e scrive commenti e messaggi in inglese, come i comandi stessi. Esegui prima lo script su un dispositivo di laboratorio.
Riferimenti
- expect(1), Expect 5.45.4 manual source (core.tcl-lang.org, tag expect-5-45-4)
- expect.c, Expect 5.45.4 (core.tcl-lang.org, tag expect-5-45-4)
- OpenSSH ssh(1) (man.openbsd.org, dated 9 October 2026)
- OpenSSH ssh_config(5): StrictHostKeyChecking, BatchMode, IdentitiesOnly (man.openbsd.org, dated 9 October 2026)
- RFC 854, Telnet Protocol Specification (May 1983)
- The Expect suite's device profiles (src/content/expect/device-profiles.ts): Cisco IOS XE 17.x, F5 TMSH Reference v17, FortiOS 7.6.8, Switch Engine 33.7.1, Fabric Engine 9.4