Skip to content

Instantly share code, notes, and snippets.

@SebastianGrans
Created December 3, 2023 20:00
Show Gist options
  • Save SebastianGrans/7052319b21ed121b9612e805e6799bd6 to your computer and use it in GitHub Desktop.
Save SebastianGrans/7052319b21ed121b9612e805e6799bd6 to your computer and use it in GitHub Desktop.
Using Expect in Windows

Using Expect in Windows

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:

  1. Install Expect in your WSL distro

  2. Place your expect sript in your WSL home folder ~/script.expect (remember to make it executable)

  3. Then add the following to your PowerShell profile file (it's located in $profile)

    function expectscript([string]$ip) {
      wsl --cd ~ -- ./script.expect $ip
    }
  4. Source your profile . $profile, and you should now be able to run expectscript!

The Expect script

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment