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