1#!/usr/bin/expect --
2
3proc usage {} {
4  puts stderr "Usage: sshauser \[ --retry \] port user \[ command ... \]"
5  exit 22
6}
7
8if { $argc < 2 } {
9    usage
10}
11
12set arg 0
13set retry 0
14if { [lindex $argv $arg] == "--retry" } {
15  set retry 1
16  set arg [expr $arg + 1]
17}
18set offset [lindex $argv $arg]
19set arg [expr $arg + 1]
20set username [lindex $argv $arg]
21set arg [expr $arg + 1]
22set command [lrange $argv $arg $argc]
23
24set password "alpine"
25set timeout 60
26
27# trap SIGWINCH and pass to spawned process
28trap {
29 set rows [stty rows]
30 set cols [stty columns]
31 stty rows $rows columns $cols < $spawn_out(slave,name)
32} WINCH
33
34set continue 1
35while { $continue } {
36	set continue $retry
37	spawn ssh -o NoHostAuthenticationForLocalhost=yes -p $offset $username@localhost
38	while { 1 } {
39		expect "Are you sure you want to continue connecting (yes/no)" {
40			send "yes\r" 
41		} "password:" { 
42			send "$password\r" 
43		} "#" {
44			 if { $argc > 2 } { send "$command\r" }
45			 interact
46			 break
47		} "mobile" {
48			 if { $argc > 2 } { send "$command\r" }
49			 interact
50			 break
51		} "ssh: connect to host localhost port $offset: Connection refused" {
52			if { $retry } {
53			  wait
54			  set continue $retry
55			  send_user "conection lost... retrying in 5 seconds.\n"
56			  sleep 5
57			}
58			break
59		} "ssh_exchange_identification: read: Connection reset by peer" {
60			if { $retry } {
61			  wait
62			  set continue $retry
63			  send_user "Device rebooting waiting for 15 seconds.\n"
64			  sleep 15
65			}
66			break
67		}
68	}
69}
70