expect -------把交互式命令变为非交互式命令使用

一、expect

当你不能把交互式的命令变成非交互式的命令时使用

spawn生成           expect捕获             send发送

1.方法:

设置ssh下次登陆不再需要密码
ssh-keygen --------设置公钥
ssh-copy-id -i root@10.18.41.62 ---------把公钥传给10.18.41.62
ssh-add ---------挂钥匙环
cd /root/.ssh-------查看公钥私钥
rm -rf  /root/.ssh/* -----删除公钥文件

w命令-->用来查看登录者的信息及他们的行为

安装扫描

nmap -v -sP 10.18.41.0/24 -------扫描该网段的IP


2.例题:检测系统是否已经安装expext

#!/bin/bash
ip="172.16.70.251"
if [ -f /usr/bin/expect ];then
:
else
yum -y    install  expect
fi

if grep 251 /etc/hosts
then
:
else
echo "$ip test.up.com">> /etc/hosts
fi


3.设置给其他用户非交互式传送公钥

例1:生成并拷贝ssh_key到远程机器,再次登陆时免密码

vim  expect.sh

/usr/bin/expect <<EOF   -------spawn生成expect捕获send发送
set timeout 300       设置超时时间--(如果没有设置timeout,或者timeout不够长,那么就不能保证spawn的效果,由于网络原因,有可能超时,先send密码了,之后才返回要expect密码。)
spawn ssh-keygen
expect "Enter file in which to save the key (/root/.ssh/id_rsa):"
send "\n"
expect "Enter passphrase (empty for no passphrase):"
send "\n"
expect "Enter same passphrase again:"
send "\n"

spawn ssh-copy-id 172.16.70.251
expect {
"yes/no" { send "yes\n"; exp_continue }
"root@172.16.70.251's password:" { send "mima\n"}
}


expect  eof   ----不同与#!/usr/bin/expect  ,所以注意一定添加
EOF

ssh-add

2.传输公钥之后可以操作:

ssh  ip   "命令"

例子:ssh  10.18.41.62  "rm  -rf   /tmp/*"


3.远程拷贝:(谁是远程谁加IP)

scp   10.18.41.62:/a.txt     /tmp


4.例子:编写脚本实现(expect自动安装)

#!/bin/bash
#expect实例
#author:bijz
read -p "Your Name: " name

ip="172.16.70.251"
if [ -f /usr/bin/expect ];then
:
else
yum install expect -y
fi


5.批量修改用户密码

for i in `cat 1.txt`
do
/usr/bin/expect <<EOF
spawn passwd $i

expect "password:"
send "$i\n"

expect "password:"
send "$i\n"

expect eof
EOF
done




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值