expect工具的使用

expect工具的使用

expect 脚本的后缀名可以为sh、exp、expect

例子1——ssh连接主机

# !/bin/expect

spawn ssh root@centso71

expect {
    "yes/no" {send "yes\r";exp_continue}
    "password:" {send "123\r"};
}
interact

ssh改进版

# !/bin/expect

set ip 182.168.56.162
set user root
set passwd 123
set timeout 5

spawn ssh $user@$ip

expect{
    "yes/no" {send "yes\sr";exp_continue}
    "password:" {send "$passwd\r"};
}
interact

使用位置参数

set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd 123
set timeout 5

spawn ssh $user@$ip

expect{
    "yes/no" {send "yes\sr";exp_continue}
    "password:" {send "$passwd\r"};
}
# interact 不使用交互模式
expect "#"
send "ls\r"

例子2——获取IP、推送公钥

#!/bin/bash

>ip.txt
passwd=123

# 测试expect是否安装
rpm -q expect &>/dev/null
if [ $? -ne 0 ];then
    yum -y install expect
fi

# 测试公钥是否存在,不存在则创建
if [ ! -f ~/.ssh/id_rsa ];then
    ssh-keygen -P "" -f ~/.ssh/id_rsa
fi

for i in {2..254}
do
    {
        ip=192.168.56.$i
        ping -c1 -W1 $ip &>/dev/null
        if [ $? -eq 0 ];then
            echo "$ip" >> ip.txt
            expect <<-EOF
            spawn ssh-copy-id $ip
            expect {
                "yes/no" {send "yes\r"; exp_continue}
                "password:" {send "$password\r"}
            }
            expect eof
            EOF
        fi
    }&
done
wait
echo "finish......"
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值