I am trying to build and expect script to log into multiple aix boxes and change password. I need for the script to terminate if it cannot log into a server because the username or password is wrong.
#!/usr/bin/expect
set timeout 1
set host [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set uh "Unknown host"
set ivl "\[compat\]\: You entered an invalid login name or password"
set lg "login"
set pwd "Password:"
set prp "$host"
proc login {user password} {
expect "Login:"
send "$user\r"
expect "Password:"
send "$password\r"
}
spawn telnet $host
expect {
$uh {
send_user "Unknown Host\n"
}
$lg {
send $user\r ; exp_continue
}
$pwd {
send $password\r
expect {
"#" {send hostname\r}
"$" {send hostname\r}
">" {send hostname\r}
$ivl { send_error "Invalid Username or Password\n" }
}
}
}
expect closed
exit 0
This is an example to try:
#!/usr/bin/expect
set timeout 1
set host [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
proc login {user password} {
expect -re "(Login|login).*:.*" { exp_send "$user\r"; exp_continue } \
-re "(Password|password).*:.*" { exp_send "$password\r"; exp_continue } \
-re "(#|\$|>)" { return 0 } \
eof { puts "***Error connecting to($host)."; return 1 }
timeout { puts "***Error connecting to($host)."; return 1 }
}
}
spawn telnet $host
set login_results [login $user $password]
# If successful connection, continue, else exit denoting error occured.
if { $connect_results == 0 } {
# Successful telnet session so exit with zero status
exit 0
}
# Error connecting to host so exit with non-zero status
exit 1
There is another expect telnet example here:
Expect - Wikipedia, the free encyclopedia
Expect scripts for automatic login with telnet and SSH Sasha's weblog
The scrip keeps coming up with an error.
invalid command name "}"
while executing
"}"
(file "./pwd2.exp" line 16)
Ok, Try this:
#!/usr/bin/expect
set timeout 10
set host [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
proc login {host user password} {
expect {
"nkown host" { puts "***Host($host) is unkown."; return 1 }
"onnection refused" { puts "***Connection was refused to host($host)."; return 1 }
"Escape character is '^]'." { exp_continue }
-re "Login:.*$|login:.*$" { exp_send "$user\r"; exp_continue }
-re "Password:.*$|password:$" { exp_send "$password\r"; return 0 }
timeout { puts "***Telnet timed out waiting for host($host)."; return 1 }
}
}
catch { spawn -noecho telnet $host }
set login_results [login $host $user $password]
# If successful connection, continue, else exit denoting error occured.
if { $login_results == 0 } {
puts "\r***Connected; You are on the command line..."
interact
# Successful telnet session so exit with zero status
exit 0
}
# Error connecting to host so exit with non-zero status
exit 1
1 Like