Expect scripts

From sheep
Jump to navigation Jump to search

ssh interactive login

#!/usr/bin/expect -f
log_user 0

proc do_exit {msg} {
    puts stderr $msg
    exit 1
}

set user [lindex $argv 0]
set password [lindex $argv 1]
set ipaddr [lindex $argv 2]
#send_tty "password $password\n"
set newpassword [lindex $argv 3]
set timeout 20

# now connect to remote UNIX box (ipaddr) with given script to execute
spawn ssh $user@$ipaddr
#spawn cat
match_max 100000
# Look for passwod prompt
expect { 
	# login failed
	"Permission denied*" { do_exit "$ipaddr incorrect password" }
	"Are you sure you want to continue" { send "yes\r"; exp_continue}
	# password prompt
	"*?assword:*" { send -- "$password\r"; exp_continue}
	{[$]}
}

#clear out buffer
expect -re $

# check group
send -- "id\r"
expect "uid*)"
send_tty "$ipaddr $expect_out(0,string)\n"

#clear out buffer
expect -re $

send -- "exit\r"
expect eof

close $spawn_id

change password (centos)

#!/usr/bin/expect -f
log_user 0

proc do_exit {msg} {
    puts stderr "$msg"
    exit 1
}

set user [lindex $argv 0]
set password [lindex $argv 1]
set ipaddr [lindex $argv 2]
#send_tty "password $password\n"
set newpassword [lindex $argv 3]
set timeout 30

# now connect to remote UNIX box (ipaddr) with given script to execute
spawn ssh $user@$ipaddr
match_max 100000

# Look for passwod prompt
expect { 
	# login failed
	"Permission denied*" { do_exit "$ipaddr incorrect password" }
	"Are you sure you want to continue" { send "yes\r"; exp_continue}
	# password prompt
	"*?assword:*" { send -- "$password\r"; exp_continue}
	{[$]}
}

#clear out buffer
expect -re $

send -- "passwd\r"

expect "*current*password"
send -- "$password\r"
expect "*ew*password*" 
send -- "$newpassword\r"
expect {
	"Retype*password" {send -- "$newpassword\r"}
	"BAD PASSWORD*" { do_exit "$ipaddr Poor new password:- $expect_out(0,string)" }
}
expect { 
	"*updated successfully" { send_tty "$ipaddr has a new password\n" }
	timeout {
		do_exit "$ipaddr timeout buffer was $expect_out(buffer)" }
}
send -- "exit\r"
expect eof

close $spawn_id