shell脚本-7

一、expect脚本远程登录

1、上线代码:所谓上线,就是把开发人员开发的代码发布到线上环境,

2、安装expect 

yum install -y expect

3、编辑登录脚本

#! /usr/bin/expect
set host "192.168.134.131"
set passwd "root1234"
spawn ssh root@$host
expect {
"yes/no" {send "yes\r"; exp_continue}          #遇见“yes/no” ,则发送yes,exp_continue表示继续
"password:" { send "$passwd\r" }                 #遇见“password:”,则发送密码
}
interact

4、给予权限

chmod a+x 1.expect 

二、expect脚本远程执行命令

1、编辑执行命令脚本2.expect

#!/usr/bin/expect
set user "root"
set passwd "root1234"
spawn ssh [email protected]
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"                                                         
send "touch /tmp/hk.txt\r"                                      #* 代表任意字符,遇见]*,创建hk.txt
expect "]*"
send "echo 1212 > /tmp/hk.txt\r"                          #遇见]*,写入1212
expect "]*"
send "exit\r"                                                         #退出

2、给予权限

 chmod a+x 2.expect

 

三、expect脚本传递参数

 1、编辑传递参数的脚本3.expect

#!/usr/bin/expect
set user [lindex $argv 0]                          #设置参数
set host [lindex $argv 1]
set passwd "root1234"
set cm [lindex $argv 2]
spawn ssh $user@$host
expect {
"yes/no" { send "yes\r" }
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"

2、给予权限

 chmod a+x 3.expect 

执行多个命令时。可设置多个参数,也可多个命令放在双引号内,用分号符隔开。

猜你喜欢

转载自www.cnblogs.com/wbjy123linux/p/8947428.html