Copy Code code as follows:
#!/usr/bin/expect-f
Set Timeout 30
Set Host "192.168.1.198"
Spawn ssh $host
Expect_before "No"? {
Send "yes\r"}
Sleep 1
Expect "Password:"
Send "123456\r"
Expect "*#"
Send "echo my name is Fivetrees >/root/fivetrees.txt\r"
Interact
##----------------------------
Copy Code code as follows:
[Root@fivetrees ~]# Cat expect
#!/usr/bin/expect
For {set i} {$i <=} {incr i} {
Set Timeout 30
Set ssh_user [lindex $argv 0]
Spawn ssh-i. ssh/$ssh _user abc$i.com
Expect_before "No"? {
Send "yes\r"}
Sleep 1
Expect "password*"
Send "hello\r"
Expect "*#"
Send "echo Hello expect! >/tmp/expect.txt\r "
Expect "*#"
Send "echo\r"
}
Exit
##-------------------------
Copy Code code as follows:
#!/usr/bin/expect
If {$ARGC!=2} {
Send_user "usage:./expect ssh_user password\n"
Exit
}
foreach I {11 12} {
Set Timeout 30
Set ssh_user [lindex $argv 0]
Set password [lindex $argv 1]
Spawn ssh-i. ssh/$ssh _user root@xxx.yy.com
Expect_before "No"? {
Send "yes\r"}
Sleep 1
Expect "Enter Passphrase for key*"
Send "password\r"
Expect "*#"
Send "echo Hello expect! >/tmp/expect.txt\r "
Expect "*#"
Send "echo\r"
}
Exit
##---------------------------
Copy Code code as follows:
#!/usr/bin/expect
Set Timeout 20
If {$ARGC < 1} {
Puts "Usage:script IP"
Exit 1
}
# Replace your own username
Set User "username"
#替换你自己的登录密码
Set Password "YourPassword"
foreach IP $argv {
Spawn ssh $user @ $IP
Expect \
"(yes/no)?" {
Send "yes\r"
Expect "Password:?" {
Send "$password \ r"
}
} "Password:?" {
Send "$password \ r"
}
Expect "\$?"
# Replace the command you want to execute
Send "last\r"
Expect "\$?"
Sleep 10
Send "exit\r"
Expect EOF
}
How to use
Script_name ip1 ip2 IP3 ...
##---------------------
Copy Code code as follows:
#!/bin/sh
#-*-Tcl-*-\
EXEC tclsh $ "$@"
Package Require Expect
Set username [lindex $argv 0]
Set password [lindex $argv 1]
Set argv [Lrange $argv 2 end]
Set Prompt "(%|#|\\$) $"
foreach IP $argv {
Spawn ssh-t $username @ $ip SH
Lappend IDs $spawn _id
}
Expect_before-i IDs EOF {
Set index [Lsearch $ids $expect _out (spawn_id)]
Set IDs [Lreplace $ids $index $index]
If [llength $ids] Exp_continue
}
Expect-i IDs "(yes/no) \?" {
Send-i $expect _out (spawn_id) yes\r
Exp_continue
-I IDs "Enter passphrase for key" {
Send-i $expect _out (spawn_id) \ r
Exp_continue
}-I IDs "Assword:" {
Send-i $expect _out (spawn_id) $password \ r
Exp_continue
}-I ids-re $prompt {
Set spawn_id $expect _out (spawn_id)
Send "echo hello; Exit\r "
Exp_continue
} Timeout {
Exit 1
}