免交互expect
[root@m01 ~]# yum provides mkpasswd
expect-5.45-14.el7_1.x86_64
mkpasswd -l 10 -d 3 -c 3 -C 3 -s 1 #指定密码长度,数字个数,大小写字母数,特殊符号数
1.安装expect
[root@m01 ~]# yum install -y expect
[root@web01 ~]# rpm -ql expect
/usr/bin/autoexpect
/usr/bin/dislocate
/usr/bin/expect #可以TAB 和 使用相对路径执行
2.编写expect脚本,expect和shell,awk,sed一样,都是一门语言有自己的脚步格式
vim ep.sh
#指定写入的语言是哪种
vim dz.sh
##!/bin/bash/python3
#!/usr/bin/expect
#指定要连接的主机的IP
set ip 10.0.0.8
#指定密码
set pass 1
#超时时间
set timeout 30
spawn ssh root@$ip
expect {
"(yes/no)" {send "yes\r"; exp_continue}
"password:" {send "$pass\r"}
}
expect "root@*" {send "df -h\r"}
expect "root@*" {send "exit\r"}
expect eof
[root@web01 ~]# expect dz.sh #执行方式
spawn ssh root@10.0.0.8
root@10.0.0.8's password:
Last login: Tue May 12 14:11:29 2020 from 10.0.0.1
[root@web02 ~]# df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 476M 0 476M 0% /dev
tmpfs 487M 0 487M 0% /dev/shm
tmpfs 487M 7.7M 479M 2% /run
tmpfs 487M 0 487M 0% /sys/fs/cgroup
/dev/sda3 19G 1.6G 17G 9% /
/dev/sda1 497M 124M 374M 25% /boot
tmpfs 98M 0 98M 0% /run/user/0
[root@web02 ~]# exit
logout
Connection to 10.0.0.8 closed.
免交互sshpass
1.安装sshpass
[root@m01 ~]# yum install -y sshpass
2.使用sshpass命令
[root@m01 ~]# sshpass -p 123456 ssh root@10.0.0.51
[option]
-p:指定密码
-f:从文件中取密码
-e:从环境变量中取密码
-P:设置密码提示
推送公钥
vim /root/mjh.sh
#!/bin/bash
pass='1'
ip='172.16.1.'
rpm -q sshpass >/dev/null
[ echo $? -ne 0 ];yum install -y sshpass
[ ! -d /root/.ssh/id_rsa.pub ];
ssh-keygen -t rsa -P "" -f /root/.ssh/id_rsa
rm -rf /root/.ssh/known_hosts
for i in 5 6 7 8 9 31 41 51 52 53 54 61 200;
do
sshpass -p $pass ssh-copy-id -i /root/.ssh/id_rsa.pub -o stricthostkeychecking=no root@${ip}${i}
done
chmod 600 /root/mjh.sh