expect遠程自動登錄bash
用法1、遠程自動登錄腳本,服務端須要安裝expect和openssh-clientsssh
[root@localhost ~]# cat login.expectide
#! /usr/bin/expectspa
set host "192.168.1.2"ip
set passwd "12345678"同步
spawn ssh root@$hostit
expect {class
"yes/no" { send "yes\r"; exp_continue}cli
"assword:" { send "$passwd\r" }file
}
interact
用法2、登錄後執行命令而後退出
[root@localhost ~]# cat 11.expect
#!/usr/bin/expect
set user "root"
set host "192.168.1.2"
set passwd "12345678"
spawn ssh $user@$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"
send "touch /tmp/12.txt\r"
expect "]*"
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
send "exit\r"
用法3、expect傳遞參數
[root@localhost ~]# cat 11.expect
#!/usr/bin/expect
# 第一個參數爲用戶名
set user [lindex $argv 0]
# 第二個參數爲IP
set host [lindex $argv 1]
# 第三個參數爲密碼
set passwd [lindex $argv 2]
# 第四個參數爲執行的命令
set cm [lindex $argv 3]
# ssh遠程登錄
spawn ssh $user@$host
# expect模塊自動執行
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
[root@localhost ~]## 運行方式,執行腳本的時候須要在後面指定4個參數,每一個參數之間用空格分開
[root@localhost ~]# ./11.expect root 192.168.1.2 12345678 "cat /etc/passwd > /tmp/111.txt"
用法4、同步文件,服務端和客戶端都要安裝rsync
[root@localhost ~]# cat 11.expect
#!/usr/bin/expect
set passwd "111111"
set file "/tmp/11.txt"
spawn rsync -av $file root@192.168.10.29:$file
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
用法5、指定IP列表
[root@localhost ~]# cat 1.expect
#!/usr/bin/expect
set host [lindex $argv 0]
set passwd "111111"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"assword:" { send "$passwd\r" }
}
interact
[root@localhost ~]# cat 1.sh
#!/bin/bash
for ip in `cat ip.txt`
do
./1.expect $ip
done
[root@localhost ~]# cat ip.txt
192.168.1.2
192.168.1.3
用法6、指定IP列表,文件列表
[root@localhost ~]# vi 1.expect
#!/usr/bin/expect
set host [lindex $argv 0]
set file [lindex $argv 1]
set passwd "111111"
spawn rsync -av $file root@$host:$file
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
[root@localhost ~]# vi 1.sh
#!/bin/bash
for ip in `cat ip.txt`
do
for file in `cat file.txt`
do
./1.expect $ip $file
done
done
[root@localhost ~]# cat file.txt
/tmp/1.txt
/tmp/2.txt
[root@localhost ~]# cat ip.txt
192.168.1.2
192.168.1.3