Search code examples
bashshellcommand-lineexpect

"Expect" command line script to connect to VPN and enter password


I am trying to write an "Expect" script to connect to a VPN... Trying to write and expect (https://likegeeks.com/expect-command/) script to connect to a vpn, is this the right idea:

The commands to connect are:

sudo vpnName [ENTER] *Password* [ENTER] Random number 1-100 [ENTER] [ENTER]

So the expect script would be something like:

#!/usr/bin/expect -f 
set randNum [(( ( RANDOM % 100 )  + 1 ))]
send -- "sudo vpnName\r"
send -- "*password*\r"
send -- "randNum\r \r"

Solution

  • In expect, you need to spawn a process before you can interact with it:

    #!/usr/bin/expect -f 
    set randNum [expr {int(rand()*100) + 1}] # as per @Sorin's answer
    
    spawn sudo vpnName
    
    expect "assword"          # wait for the password prompt
    send -- "*password*\r"
    
    expect "whatever matches the random number prompt"
    send -- "$randNum\r\r"
    
    # this keeps the vpn process running, but returns interactive control to you:
    interact
    

    A tip: while debugging expect code, launch it with expect -d -f file.exp -- this is very valuable to let to see if your expect patterns are matching as you think they should.