加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux expect详解

发布时间:2020-12-13 22:34:13 所属栏目:Linux 来源:网络整理
导读:expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。 expect自动交互流程: spawn启动指定进程---expect获取指定关键字---send向指定程序发送指定字符---执行完成退出. expect常用命令总结: spawn

expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。

expect自动交互流程:

spawn启动指定进程---expect获取指定关键字---send向指定程序发送指定字符---执行完成退出.

expect常用命令总结:

spawn               交互程序开始后面跟命令或者指定程序
expect              获取匹配信息匹配成功则执行expect后面的程序动作
send exp_send       用于发送指定的字符串信息
exp_continue        在expect中多次匹配就需要用到
send_user           用来打印输出 相当于shell中的echo
exit                退出expect脚本
eof                 expect执行结束 退出
set                 定义变量
puts                输出变量
set timeout         设置超时时间

示例:

1.ssh登录远程主机执行命令,执行方法 expect 1.sh 或者 ./1.sh

# vim 1.sh?

#!/usr/bin/expect

spawn ssh [email?protected] df -Th
expect "*password"
send "123456n"
expect eof

2. ssh远程登录主机执行命令,在shell脚本中执行expect命令,执行方法sh 2.sh、bash 2.sh 或./2.sh都可以执行.

#!/bin/bash

passwd=‘123456‘

/usr/bin/expect <<-EOF

set time 30
spawn ssh [email?protected] df -Th
expect {
"*yes/no" { send "yesr"; exp_continue }
"*password:" { send "$passwdr" }
}
expect eof
EOF

3.expect执行多条命令

#!/usr/bin/expect -f

set timeout 10

spawn sudo su - root
expect "*password*"
send "123456r"
expect "#*"
send "lsr"
expect "#*"
send "df -Thr"
send "exitr"
expect eof

4. 创建ssh key,将id_rsa和id_rsa.pub文件分发到各台主机上面。

1.创建主机配置文件

[[email?protected] script]# cat host 
192.168.1.10 root 123456
192.168.1.20 root 123456
192.168.1.30 root 123456

[[email?protected] script]# ls
copykey.sh  hosts
2.编写copykey.sh脚本,自动生成密钥并分发key.
[[email?protected] script]# vim copykey.sh

#!/bin/bash

# 判断id_rsa密钥文件是否存在
if [ ! -f ~/.ssh/id_rsa ];then
 ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa
else
 echo "id_rsa has created ..."
fi

#分发到各个节点,这里分发到host文件中的主机中.
while read line
  do
    user=`echo $line | cut -d " " -f 2`
    ip=`echo $line | cut -d " " -f 1`
    passwd=`echo $line | cut -d " " -f 3`
    
    expect <<EOF
      set timeout 10
      spawn ssh-copy-id [email?protected]$ip
      expect {
        "yes/no" { send "yesn";exp_continue }
        "password" { send "$passwdn" }
      }
     expect "password" { send "$passwdn" }
EOF
  done <  hosts

?5. shell调用expect执行多行命令.

#!/bin/bash 
ip=$1  
user=$2 
password=$3 

expect <<EOF  
    set timeout 10 
    spawn ssh [email?protected]$ip 
    expect { 
        "yes/no" { send "yesn";exp_continue } 
        "password" { send "$passwordn" }
    } 
    expect "]#" { send "useradd hehen" } 
    expect "]#" { send "touch /tmp/test.txtn" } 
    expect "]#" { send "exitn" } expect eof 
 EOF  
 #./ssh5.sh 192.168.1.10 root 123456 

?

参考文档:https://www.cnblogs.com/yxh168/p/9028122.html

    ? ??https://www.cnblogs.com/lisenlin/p/9058557.html

转载自  https://www.cnblogs.com/saneri/p/10819348.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读