Issue
I am trying to write an expect script to login to a pfsense router and run a few commands. I don't seem to be able to correctly match the multiline responses from the pfsense device and answer them correctly the way I see the responses when running autoexpect and working back from there. I think my script is working in passing the password in, but the large wall of text, ending with 'Enter an option: ', that I see after logging in, isn't being matched. This is what I am hoping to run:
# Main script
set prompt {[$>?#]: }
puts "Connecting to pfSense router..."
spawn ssh -p $ssh_port -o StrictHostKeyChecking=no $username@$pfsense_router
expect {
-re "assword.*:" {
send "$password\r"
expect $prompt
# exp_continue
}
-re ".*Enter an option: " {
send "8\r"
expect $prompt
# exp_continue
}
"/root:.*" {
puts "SSH login successful."
check_gateway_status $target_host
}
"Permission denied" {
send_user "Authentication failed. Please check your credentials.\n"
exit 1
}
timeout {
send_user "Timeout while trying to connect to the router.\n"
exit 1
}
}
In order to match text looking like this:
ssh $pfsense_ip -p 3456
Password for root@$pfsense_hostname:
KVM Guest - Netgate Device ID: fa1a75cc70c259bca849
*** Welcome to pfSense 2.6.0-RELEASE (amd64) on edge1 ***
WAN (wan) -> vtnet3 -> v4: $pfsense_ip/29
LAN (lan) -> vtnet1 -> v4: 10.0.192.253/24
OPT1 (opt1) -> vtnet2 -> v4: 10.0.182.253/24
OPT2_FORMER_192_168_2_244 (opt2) -> vtnet0 ->
VTI01 (opt3) -> ipsec9 -> v4: 10.6.106.1/30
0) Logout (SSH only) 9) pfTop
1) Assign Interfaces 10) Filter Logs
2) Set interface(s) IP address 11) Restart webConfigurator
3) Reset webConfigurator password 12) PHP shell + pfSense tools
4) Reset to factory defaults 13) Update from console
5) Reboot system 14) Disable Secure Shell (sshd)
6) Halt system 15) Restore recent configuration
7) Ping host 16) Restart PHP-FPM
8) Shell
Enter an option:
How do I do this correctly?
Solution
I assume after you enter 8
to get a shell, this is where you want to run some more commands.
I'd start with
spawn ssh -p $ssh_port -o StrictHostKeyChecking=no $username@$pfsense_router
expect {
-re "assword.*:" {
send "$password\r"
exp_continue
}
"Permission denied" {
send_user "Authentication failed. Please check your credentials.\n"
exit 1
}
timeout {
send_user "Timeout while trying to connect to the router.\n"
exit 1
}
-re {Enter an option:\s*$} {
send "8\r"
}
}
expect -re $prompt
# now start sending commands and expecting the prompt.
Answered By - glenn jackman Answer Checked By - Clifford M. (WPSolving Volunteer)