当你不能把交互式的命令变成非交互式的命令时使用
spawn生成 expect捕获 send发送
1.方法:
设置ssh下次登陆不再需要密码
ssh-keygen --------设置公钥
ssh-copy-id -i [email protected] ---------把公钥传给10.18.41.62
ssh-add ---------挂钥匙环
cd /root/.ssh-------查看公钥私钥
rm -rf /root/.ssh/* -----删除公钥文件
w命令-->用来查看登录者的信息及他们的行为
安装扫描
nmap -v -sP 10.18.41.0/24 -------扫描该网段的IP
2.例题
#!/bin/bash
ip="172.16.70.251"
if [ -f /usr/bin/expect ];then
:
else
yum install expect -y
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 }
"[email protected]'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