跳板机小脚本

高阶版

1
2
3
4
5
6
7
8
9
mkdir /shell
cat <<'EOF' >/shell/list
192.168.0.60
192.168.0.61
192.168.0.62
192.168.0.63
192.168.0.64
192.168.0.65
EOF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
cat <<'EOF' >/shell/ssh-keygen-root.sh
#!/bin/bash

# 远程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

# 以进程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
{
# 添加公钥到远程主机
/usr/bin/expect <<EOF
set timeout 5
spawn ssh-copy-id -i /root/.ssh/id_dsa.pub root@$line
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
EOF

1
2
# 登陆shell 执行判断如果不是root用户则启动跳板机脚本
echo '[ $UID -ne 0 ] && . /shell/stepping-stones.sh'>/etc/profile.d/stepping-stones.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
cat <<'EOF' >/shell/ssh_key_useradd.sh
#!/bin/bash
user='root'
n_user='okok5'
passwd='123456'
useradd $n_user && echo $passwd | passwd --stdin $n_user;
su - $n_user -c "ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa"

for ip in $(cat ./list);
do
ssh $user@$ip <<eeooff
useradd $n_user && echo 123456 | passwd --stdin $n_user
su - $n_user -c "ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa"
eeooff

# 上传公钥
/usr/bin/expect <<EOF
set timeout 10
spawn ssh-copy-id -i /home/$n_user/.ssh/id_dsa.pub $n_user@$ip
expect {
"(yes/no)?" { send "yes\r"; exp_continue }
"password:" { send "$passwd\r" }
}
expect eof
EOF
done
EOF

1
2
3
4
5
6
7
cat <<'EOF' >/shell/ssh_key_del.sh
#!/bin/bash
for ip in $(cat ./list);
do
ssh -n $user@$ip "sed -i '/\"$key\"/d' /home/$duser/.ssh/authorized_keys"
done
EOF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
cat <<'EOF' >/shell/stepping-stones.sh
#!/bin/bash

# 忽略中断信号
trapper(){
trap ':' INT EXIT TSTP TERM HUP
}

main(){
while :
do
trapper
# clear
i=1
while read line
do
echo -e "\t $i) $line"
arr_line[$i]=$line
let i++
done < ./list

read -p "Pls input a num :" num
   # 如果输入为空
   [ -z "$num" ] && { echo 'Error: 请输入IP地址前的数字编号'; continue; }
   # 如果输入的不是整数
   [ -n "`echo $num | sed 's/[0-9]//g'`" ] && { echo 'Error: 请输入IP地址前的数字编号'; continue; }
   # 如果输入的不存在
   [ $num -gt `cat /shell/list | wc -l` ] && { echo 'Error: 你输入的编号不存在'; continue; }
echo "login in $num) ${arr_line[$num]}"
ssh ${arr_line[$num]}
done
}

main
EOF