Shell expect 实战案例

网友投稿 875 2022-09-02

Shell expect 实战案例

Shell expect 实战案例

1、需要向集群的机器中执行命令,或者修改某个配置

环境准备:三台虚拟机 ip 为 192.168.0.102 192.168.0.107 192.168.0.108

方法1采用ssh root@ip “cmd”的方式

1) 开发expect自动交互命令,文件名为exec_cmd1.exp

#!/usr/bin/expect

set ip [lindex $argv 0]    #expect的的位置参数传入ip

set cmd [lindex $argv 1]     #expect的第2个位置参数需要执行的命令

set password "zhangbichen"     #设置root的paasword

spawn ssh root@$ip "$cmd"

expect {

"yes/no" {send "yes\r";exp_continue}

"password" {send "$password\r"}

}

expect eof

2) 使用shell循环在执行expect命令,batch_exec_cmd1.sh在各个多个主机上交互执行。

#!/usr/bin/bash

cmd=$1

if [ $# -ne 1 ]

then

echo $"usage:$0 cmd"

exit 1

fi

ip_list=(192.168.0.107 192.168.0.102 192.168.0.108)

for ip in ${ip_list[@]}

do

echo $ip

expect exec_cmd1.exp $ip "$cmd"执行expect脚本传入expect设置的两个位置参数

done

方法2采用交互登录到命令行时发送命令执行

[root@192 scripts]# cat exec_cmd.exp

#!/usr/bin/expect

set host [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

set root_password [lindex $argv 3]

spawn ssh $user@$host

set timeout 1

expect {

"yes/no" {send "yes\r";exp_continue}

"password" {send "$password\r"}

}

expect "$"

send "su - root\r"

expect "Password"

send "${root_password}\r"

expect "#" {send "cp /etc/profile /etc/profile.bak\r"}

expect eof

批量执行expect脚本

#!/urs/bin/bash

ip_list=(192.168.0.107 192.168.0.102)

for ip in ${ip_list[@]}

do

echo $ip

expect exec_cmd.exp $ip test01 yankefei yankefei

done

注意:一般生产环境都是先用普通用户登录,在切换root用户登录, 用户名和密码可以直接定义到expect脚本中

2、批量发送文件

1)开发expect自动交互脚本

[root@192 scripts]# cat send_file.exp

#!/usr/bin/expect

set file [lindex $argv 0]

set host [lindex $argv 1]

set remote_dir [lindex $argv 2]

set password "zhangbichen"

spawn scp -P22 -rp $file root@$host:${remote_dir}

set timeout 1

expect {

"yes/no" {send "yes\r";exp_continue}

"password" {send "$password\r"}

}

expect eof

2)开发循环批量发送脚本

[root@192 scripts]# cat batch_send.sh

#!/urs/bin/bash

file=$1

remote_dir=$2

ip_list=(192.168.0.107 192.168.0.102)

for ip in ${ip_list[@]}

do

echo $ip

expect send_file.exp $file  $ip  ${remote_dir}

done

3、批量在所有服务器上执行shell脚本

1)按照章节2批量发送文件的例子将将脚本发送到所有服务器的指定目录

2)按照章节1的在所有机器上执行命令 sh  batch_exec_cmd1.sh “source /opt/108.sh”

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:【JS题解】牛客网JS篇1-10题
下一篇:php中Session使用方法详解,你会了吗
相关文章

 发表评论

暂时没有评论,来抢沙发吧~