ssh批量免密钥

ssh推送密钥

#!/bin/bash

# 远程root密码
passwd='redhat'

# 主机列表
cat <<'EOF' >./list
192.168.2.60 node00
192.168.2.61 node01
192.168.2.62 node02
192.168.2.63 node03
192.168.2.64 node04
192.168.2.65 node05
EOF

# hosts
cat ./list >>/etc/hosts

# 生成密钥
[ -f ~/.ssh/id_dsa ] || { ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa; }

# 安装 expect
[ -f /usr/bin/expect ] || { yum -y install expect; }

# 循环list 文件
while read -r line
do
    /usr/bin/expect <<EOF
    set timeout 5
    spawn ssh-copy-id -i /root/.ssh/id_dsa.pub root@$host
    expect {
        "(yes/no)?" { send "yes\r"; exp_continue }
        "password:" { send "$passwd\r" }
    }
    expect eof
EOF
done < ./list

多线程ssh推送密钥

#!/bin/bash

# 遇到终止信号则退出
trap "exit 0" 2

# 主机列表
cat <<'EOF' >./list
192.168.2.60 node00
192.168.2.61 node01
192.168.2.62 node02
192.168.2.63 node03
192.168.2.64 node04
192.168.2.65 node05
EOF

# hosts
cat ./list >>/etc/hosts

# 远程root密码
passwd='redhat'

# 生成密钥
[ -f ~/.ssh/id_dsa ] || { ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa; }

# 安装 expect
[ -f /usr/bin/expect ] || { yum -y install expect; }

# 自定义并发数
thead_num=4

# 自定义并发数
thead_num=4

# 以进程ID号命名管道文件
tmp_fifo_file="/tmp/$$.fifo"

# 创建临时管道文件
mkfifo $tmp_fifo_file

# 以读写方式打开tmp_fifo_file管道文件,文件描述符为4,也可以取3-9任意描述符
exec 4<>$tmp_fifo_file

# 删除临时管道文件,也可不删除
rm -f $tmp_fifo_file

# 利用for循环向管道中输入并发数量的空行
for ((i=0;i<$thead_num;i++))
do
    #输出空行到定义的文件描述符4上
    echo >&4
done 

# 循环list 文件
while read -r line
do
    read -u4
{
    # 取出IP
    host=$(echo $line | awk '{print $2}')

    # 添加公钥到远程主机
    /usr/bin/expect <<EOF
    set timeout 5
    spawn ssh-copy-id -i /root/.ssh/id_dsa.pub root@$host
    expect {
        "(yes/no)?" { send "yes\r"; exp_continue }
        "password:" { send "$passwd\r" }
    }
    expect eof
EOF
    echo "" >&4
} &
done < ./list

# 等待所有后台进程执行完成
wait

#关闭文件描述符的读
exec 4<&-

#关闭文件描述符的写
exec 4>&-
exit 0

快速找出某个网段的IP使用情况

#!/bin/bash

for num in {1..254}
do
{
    ip="192.168.0.$num"
    ping -c3 -w3 $ip >/dev/null 2>&1
    if [ $? -eq 0 ];then
        echo $ip is ok
    else
        echo $ip is null
    fi
} &
done