Tcl Expect Scripts - Auto SSH Logins

When automating tasks with shell scripts, you may stumble at points that require user interaction, such as password authentication when checking out an SVN repository. One can handle these events by creating expect scripts. Below is an example script that I put together for SSHing into another computer using a password.

Be careful how you use this script, e.g. I don't recommend storing passwords in files on your computer, but asking the user their details at the beginning of your installation script and passing them to this script later isn't a bad idea.
#!/usr/bin/expect


# Set the time allowed to wait for a given response. SEt to 30 seconds because it can take a while
# for machines to respond to an ssh request.
set timeout 30000


proc connectToServer { user host password port } {

    set address $user
    append address "@"
    append address $host
    
    puts "Connecting to server: $host"

    spawn ssh $address -p $port
    expect {
        {*password: } {
            send "$password\n" 
            interact
        }
        {The authenticity of host*} {
            send "yes\n"
            expect {
                {*password: } {
                    send "$password\n"
                    interact
                }
            }
        }
        "*No route to host" { puts "No route to host" }
        eof {puts "Woops there was an eof"}
        timeout {puts "Timed out"}
    }
}


if {$argc < 3} {
    puts "Error - you need to provide at least 3 arguments"
    puts "* user"
    puts "* host"
    puts "* password"
    puts "* port - optional"
} else {
    set user [lindex $argv 0];
    set host [lindex $argv 1];
    set password [lindex $argv 2];
    
    # setting port argument is optional
    if {$argc > 3} {
        set port [lindex $argv 3];
    } else {
        set port 22
    }
    
    connectToServer $user $host $password $port
}

Just save that to a file (e.g. login.tcl) and call it like so:

 expect login.tcl [user] [host] [password] [port if not default 22]

No comments:

Post a Comment