My usecase for Expect is to automatically log in to a device over telnet, so that I don't have to write the password every time.
The easiest way is to simply run the expect script from WSL, but I'm lazy and want to run it directly from PowerShell. Here's how:
-
Install Expect in your WSL distro
-
Place your expect sript in your WSL home folder
~/script.expect
(remember to make it executable) -
Then add the following to your PowerShell profile file (it's located in
$profile
)function expectscript([string]$ip) { wsl --cd ~ -- ./script.expect $ip }
-
Source your profile
. $profile
, and you should now be able to runexpectscript
!
Here's a minimal example of my Expect script. It simply opens a telnet connection to a
specific IP and port. Once Expect sees the string Escape character is '^]'.
, it sends
the password, and then gives control back to me.
#!/usr/bin/expect
set timeout 10
# If no arg, use default ip.
set ip [lindex $argv 0]
if { $ip == "" } {
set ip "127.0.0.1"
}
set port "1337"
set password "correcthorsebatterystaple"
spawn telnet $ip $port
expect "Escape character is '^]'."
send "$password\r"
interact