ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

自动交互命令工具expect

2021-02-23 16:35:12  阅读:11  来源: 互联网

标签:bin 指定 send 自动 expect 交互 user


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

简介:

expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。expect自动交互流程:spawn启动指定进程---expect获取指定关键字---send向指定程序发送指定字符---执行完成退出.注意该脚本能够执行的前提是安装了expect

yum -y install expect

常用参数:

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

示例:

使用expect登录到远程主机上查看ip地址

#!/bin/bash
user="root"
ip="192.168.137.121"
passwd="ilovewy"
/usr/bin/expect <<-EOF

spawn ssh $user@$ip ip addr
set time 30
expect {
"*yes/no"
{ send "yes\r";exp_continue }
"*password:"
{ send "$passwd\r" }
}
expect eof
EOF
#!/bin/bash
#ssh 免密分发脚本
read -p "input user " user
read -p "input host_ip " host
read -p "input host_user_passwd " passwd


if [ -e "/root/.ssh/id_rsa" ] ;then
    echo "file "
else
    echo "no file"
    /usr/bin/expect <<-EOF
    spawn ssh-keygen -t rsa
    set time 30
    expect {
    "*(/root/.ssh/id_rsa):"
    { send "\n";exp_continue }
    "*(empty for no passphrase):"
    { send "\n";exp_continue}
    "*same passphrase again:"
    { send "\n";exp_continue }
    }
    expect eof
    EOF
fi
cp_rsa(){
    cd
    echo "cp rsa_pub --> $host"
    /usr/bin/expect <<-EOF
    spawn ssh-copy-id -i .ssh/id_rsa.pub $user@$host
    set time 30
    expect {
    "*connecting (yes/no)?"
    { send "yes\n";exp_continue }
    "*password:"
    { send "$passwd\n"; }
    }
    expect eof
EOF
    }
mian (){
cp_rsa
}
main

密码过期需要批量修改密码

#!/bin/bash
for i in `cat /root/soft/ip.txt`
do
    /usr/bin/expect << EOF
    spawn /usr/bin/ssh root@$i

    expect {
        "UNIX password" { send "Huawei@123\r" }
    }
    
    expect {
        "New password:" { send "xxHuzzawexxi@1234#\r" }
    }
   expect {
        "Retype new password:" { send "xxHuzzawexxi@1234#\r" }
    }
    expect "*]#"
    send "echo Huawei@123|passwd --stdin root\r"
    expect "*]#"
    send "exit\r"
    expect eof
EOF
done

标签:bin,指定,send,自动,expect,交互,user
来源: https://www.cnblogs.com/yhy223/p/14436764.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有