随机数
bash默认有一个RANDOM的变量 默认是0~32767
使用 echo $RANDOM 随机产生一个随机数
使用 set|grep RANDOM 查看上一次产生的随机数
[root@localhost admin]# echo $RANDOM
18926
[root@localhost admin]# set |grep RANDOM
RANDOM=18926
举例说明
产生0~1之间的随机数
echo $[$RANDOM%2]
产生0~2之间的随机数
echo $[$RANDOM%3]
产生0~3之间的随机数
echo $[$RANDOM%4]
...
产生0~9内的随机数
echo $[$RANDOM%10]
产生0~100内的随机数
echo $[$RANDOM%101]
产生50-100之内的随机数
echo $[$RANDOM%51+50] 50-100——>0-50——>%51 +50
产生三位数的随机数
echo $[$RANDOM%900+100] 100-999 ——>0-899——>%900 +100
实战案例
1、写一个脚本,产生一个phonenum.txt文件,随机产生以139开头的手机号 1000个,每个一行
分析:
1. 产生1000个电话号码,脚本需要循环1000次
2. 139+8位,后8位随机产生,可以让每一位数字都随机产生,$[RANDOM%10] 0-9
3. 将随机产生的数字分别保存到变量里,然后加上139保存到文件里
脚本:
#!/bin/bash
# random phonenum
# 循环1000次产生电话号码并保存到文件
for i in {1..1000}
do
n1=$[$RANDOM%10]
n2=$[$RANDOM%10]
n3=$[$RANDOM%10]
n4=$[$RANDOM%10]
n5=$[$RANDOM%10]
n6=$[$RANDOM%10]
n7=$[$RANDOM%10]
n8=$[$RANDOM%10]
echo "139$n1$n2$n3$n4$n5$n6$n7$n8" >> phonenum.txt
done
#!/bin/bash
# random phonenum
# 循环1000次产生电话号码
for ((i=1;i<=1000;i++))
do
n1=$[$RANDOM%10]
n2=$[$RANDOM%10]
n3=$[$RANDOM%10]
n4=$[$RANDOM%10]
n5=$[$RANDOM%10]
n6=$[$RANDOM%10]
n7=$[$RANDOM%10]
n8=$[$RANDOM%10]
echo "139$n1$n2$n3$n4$n5$n6$n7$n8" >> phonenum.txt
done
#!/bin/bash
i=1
while [ $i -le 1000 ]
do
n1=$[$RANDOM%10]
n2=$[$RANDOM%10]
n3=$[$RANDOM%10]
n4=$[$RANDOM%10]
n5=$[$RANDOM%10]
n6=$[$RANDOM%10]
n7=$[$RANDOM%10]
n8=$[$RANDOM%10]
echo "139$n1$n2$n3$n4$n5$n6$n7$n8" >> phonenum.txt
let i++
done
continue:继续,跳过本次循环,执行下一次循环
break:打断,执行循环体外的代码do..done外
exit:退出程序
#!/bin/bash
#create phone num file
for ((i=1;i<=1000;i++))
do
n1=$[$RANDOM%10]
n2=$[$RANDOM%10]
n3=$[$RANDOM%10]
n4=$[$RANDOM%10]
n5=$[$RANDOM%10]
n6=$[$RANDOM%10]
n7=$[$RANDOM%10]
n8=$[$RANDOM%10]
echo "139$n1$n2$n3$n4$n5$n6$n7$n8" |tee -a phonenum.txt
done
#!/bin/bash
count=0
while true
do
n1=$[$RANDOM%10]
n2=$[$RANDOM%10]
n3=$[$RANDOM%10]
n4=$[$RANDOM%10]
n5=$[$RANDOM%10]
n6=$[$RANDOM%10]
n7=$[$RANDOM%10]
n8=$[$RANDOM%10]
echo "139$n1$n2$n3$n4$n5$n6$n7$n8" |tee -a phonenum.txt && let count++
if [ $count -eq 1000 ];then
break
fi
done
执行结果:
[root@localhost shell]# vim random.sh
[root@localhost shell]# cat random.sh
# random phonenum
# 循环1000次产生电话号码并保存到文件
for i in {1..1000}
do
n1=$[$RANDOM%10]
n2=$[$RANDOM%10]
n3=$[$RANDOM%10]
n4=$[$RANDOM%10]
n5=$[$RANDOM%10]
n6=$[$RANDOM%10]
n7=$[$RANDOM%10]
n8=$[$RANDOM%10]
echo "139$n1$n2$n3$n4$n5$n6$n7$n8" >> phonenum.txt
done
[root@localhost shell]#
[root@localhost shell]# chmod +x random.sh
[root@localhost shell]# ./random.sh
[root@localhost shell]# ll
总用量 16
-rw-r--r--. 1 root root 12000 5月 6 22:57 phonenum.txt
-rwxr-xr-x. 1 root root 305 5月 6 22:57 random.sh
[root@localhost shell]# wc -l phonenum.txt
1000 phonenum.txt
[root@localhost shell]# sort -u phonenum.txt|wc -l
1000
2、在上面的1000个手机号里抽奖5个幸运观众,显示出这5个幸运观众。但只显示头3个数和尾号的4个数,中间的都用*代替
思路:
1、确定幸运观众所在的行 随机生成 RANDOM $[RANDOM%1000+1]
2、将电话号码提取出来 head 和 tail
3、显示前3个和后4个数到屏幕 取变量的一部分 ${变量值:下标:长度}
4、最后将电话号码输出到屏幕 echo ${电话号码部分}
脚本:
#!/bin/bash
#定义变量
phone=/tmp/shell/phonenum.txt
for ((i=1;i<=5;i++))
do
#定位幸运观众所在行号
line=`wc -l $phone |cut -d' ' -f1`
luck_line=$[RANDOM%$line+1]
#取出幸运观众所在行的电话号码
luck_num=`head -$luck_line $phone|tail -1`
#显示到屏幕
echo "139****${luck_num:7:4}"
echo $luck_num >> luck.txt
#删除已经被抽取的幸运观众号码
sed -i "/$luck_num/d" $phone
done
#!/bin/bash
file=/tmp/shell/phonenum.txt
for i in {1..5}
do
file_num=`wc -l $file |cut -d' ' -f1`
line=`echo $[$RANDOM%$file_num+1]`
luck=`head -n $line $file|tail -1`
echo "139****${luck:7:4}" && echo $luck >> /shell04/luck_num.txt
done
#!/bin/bash
for ((i=1;i<=5;i++))
do
file=phonenum.txt
line=`cat phonenum.txt |wc -l` 1000
luckline=$[$RANDOM%$line+1]
phone=`cat $file|head -$luckline|tail -1`
echo "幸运观众为:139****${phone:7:4}"
done
#!/bin/bash
# choujiang
phone=phonenum.txt
for ((i=1;i<=5;i++))
do
num=`wc -l phonenum.txt |cut -d' ' -f1`
line=`echo $[$RANDOM%$num+1]`
luck=`head -$line $phone |tail -1`
sed -i "/$luck/d" $phone
echo "幸运观众是:139****${luck:7:4}"
done
执行结果:
[root@localhost shell]# vim luck.sh
[root@localhost shell]# cat luck.sh
#!/bin/bash
#定义变量
phone=/tmp/shell/phonenum.txt
for ((i=1;i<=5;i++))
do
#定位幸运观众所在行号
line=`wc -l $phone |cut -d' ' -f1`
luck_line=$[RANDOM%$line+1]
#取出幸运观众所在行的电话号码
luck_num=`head -$luck_line $phone|tail -1`
#显示到屏幕
echo "139****${luck_num:7:4}"
echo $luck_num >> luck.txt
#删除已经被抽取的幸运观众号码
sed -i "/$luck_num/d" $phone
done
[root@localhost shell]# chmod +x luck.sh
[root@localhost shell]# ./luck.sh
139****4711
139****2286
139****7711
139****2112
139****0446
[root@localhost shell]# ll
总用量 24
-rwxr-xr-x. 1 root root 424 5月 6 23:26 luck.sh
-rw-r--r--. 1 root root 60 5月 6 23:29 luck.txt
-rw-r--r--. 1 root root 11940 5月 6 23:29 phonenum.txt
-rwxr-xr-x. 1 root root 305 5月 6 22:57 random.sh
[root@localhost shell]# cat luck.txt
13912824711
13918492286
13966267711
13934012112
13982180446
[root@localhost shell]# wc -l phonenum.txt
995 phonenum.txt
3、批量创建5个用户,每个用户的密码为一个随机数
思路:
1、循环5次创建用户
2、产生一个密码文件来保存用户的随机密码
3、从密码文件中取出随机密码赋值给用户
补充:
pwgen工具产生随机密码
安装:
yum -y install pwgen
语法:
pwgen [ OPTION ] [ pw_length ]
参数:
-c 密码中至少包含一个大写字母
-n 密码中至少包含一个数字
-y 密码中至少包含一个特殊符号
-s 生成完全随机密码
-1 不要在列中打印生成的密码,即一行一个密码
实例:
[root@server shell04]# pwgen -cn1 12
Meep5ob1aesa
[root@server shell04]# echo user0{1..3}:$(pwgen -cn1 12)
user01:Bahqu9haipho user02:Feiphoh7moo4 user03:eilahj5eth2R
[root@server shell04]# echo user0{1..3}:$(pwgen -cn1 12)|tr ' ' '\n'
user01:eiwaShuZo5hi
user02:eiDeih7aim9k
user03:aeBahwien8co
脚本:
#!/bin/bash
#crate user and set passwd
#产生一个保存用户名和密码的文件
echo user0{1..5}:$(pwgen -cn1 12)|tr ' ' '\n'>> user_pass.file
#循环创建5个用户
for ((i=1;i<=5;i++))
do
user=`head -$i user_pass.file|tail -1|cut -d: -f1`
pass=`head -$i user_pass.file|tail -1|cut -d: -f2`
useradd $user
echo $pass|passwd --stdin $user
done
执行结果:
[root@bobilinux shell]# vim pass.sh
[root@bobilinux shell]# cat pass.sh
#!/bin/bash
#crate user and set passwd
#产生一个保存用户名和密码的文件
echo user0{1..5}:$(pwgen -cn1 12)|tr ' ' '\n'>> user_pass.file
#循环创建5个用户
for ((i=1;i<=5;i++))
do
user=`head -$i user_pass.file|tail -1|cut -d: -f1`
pass=`head -$i user_pass.file|tail -1|cut -d: -f2`
useradd $user
echo $pass|passwd --stdin $user
done
[root@bobilinux shell]# chmod +x pass.sh
[root@bobilinux shell]# ./pass.sh
Changing password for user user01.
passwd: all authentication tokens updated successfully.
Changing password for user user02.
passwd: all authentication tokens updated successfully.
Changing password for user user03.
passwd: all authentication tokens updated successfully.
Changing password for user user04.
passwd: all authentication tokens updated successfully.
Changing password for user user05.
passwd: all authentication tokens updated successfully.
[root@bobilinux shell]# ll
total 8
-rwxr-xr-x 1 root root 354 May 7 13:17 pass.sh
-rw-r--r-- 1 root root 100 May 7 13:18 user_pass.file
[root@bobilinux shell]# cat user_pass.file
user01:Tahdei3sheKe
user02:ahSuQu1to2uo
user03:xu1OhThaethe
user04:Ueghaegi4dei
user05:eeGhai5aec3a
[root@bobilinux shell]# tail -5 /etc/passwd
user01:x:822:822::/home/user01:/bin/bash
user02:x:823:823::/home/user02:/bin/bash
user03:x:824:824::/home/user03:/bin/bash
user04:x:825:825::/home/user04:/bin/bash
user05:x:826:826::/home/user05:/bin/bash
嵌套循环
一个循环体内又包含另一个完整的循环结构,称为循环的嵌套。
在外部循环的每次执行过程中都会触发内部循环,直至内部完成一次循环,才接着执行下一次的外部循环。
for循环、while循环和until循环可以相互嵌套。
demo1:打印如下图案
1
12
123
1234
12345
#!/bin/bash
for ((y=1;y<=5;y++))
do
for ((x=1;x<=$y;x++))
do
echo -n $x
done
echo
done
demo2:打印如下图案
5
54
543
5432
54321
#!/bin/bash
for (( y=5;y>=1;y--))
do
for (( x=5;x>=$y;x--))
do
echo -n $x
done
echo
done
影响shell程序的内置命令
exit 退出整个程序
break 结束本层循环
continue 忽略本次循环,直接进行下一次循环
shift 使位置参数向左移动,默认移动1位,移动2位可以使用 shift 2
实例:
实现用户自定义输入数字,然后脚本计算和
脚本1:
for的无列表循环(循环参数列表)
[root@bobilinux shell]# vim for.sh
[root@bobilinux shell]# cat for.sh
#!/bin/bash
sum=0
for i
do
let sum=$sum+$i
done
echo sum=$sum
[root@bobilinux shell]# bash -x ./for.sh
+ sum=0
+ echo sum=0
sum=0
[root@bobilinux shell]# bash -x ./for.sh 1 2 3
+ sum=0
+ for i in '"$@"'
+ let sum=0+1
+ for i in '"$@"'
+ let sum=1+2
+ for i in '"$@"'
+ let sum=3+3
+ echo sum=6
sum=6
脚本2:
使用 shift 内置命令
[root@bobilinux shell]# vim shift.sh
[root@bobilinux shell]# cat shift.sh
#!/bin/bash
sum=0
while [ $# -ne 0 ]
do
let sum=$sum+$1
shift
done
echo sum=$sum
[root@bobilinux shell]# chmod +x shift.sh
[root@bobilinux shell]# bash -x ./shift.sh
+ sum=0
+ '[' 0 -ne 0 ']'
+ echo sum=0
sum=0
[root@bobilinux shell]# bash -x ./shift.sh 1 2 3
+ sum=0
+ '[' 3 -ne 0 ']'
+ let sum=0+1
+ shift
+ '[' 2 -ne 0 ']'
+ let sum=1+2
+ shift
+ '[' 1 -ne 0 ']'
+ let sum=3+3
+ shift
+ '[' 0 -ne 0 ']'
+ echo sum=6
sum=6
补充:扩展expect
传统登录服务器的交互操作过程:
[root@bobilinux shell]# ssh 192.168.192.130
The authenticity of host '192.168.192.130 (192.168.192.130)' can't be established.
RSA key fingerprint is f4:ad:61:e6:97:eb:b6:e3:8d:81:90:12:5c:5a:f6:68.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.192.130' (RSA) to the list of known hosts.
root@192.168.192.130's password:
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Thu May 5 22:05:31 2022 from 192.168.192.1
[root@localhost ~]#
[root@localhost ~]# hostnamectl
Static hostname: localhost.localdomain
Icon name: computer-vm
Chassis: vm
Machine ID: f2c7901488654d198cf54a1a2a5c0436
Boot ID: f6791a006495409b92d204e7c321dfd0
Virtualization: vmware
Operating System: CentOS Linux 8
CPE OS Name: cpe:/o:centos:centos:8
Kernel: Linux 4.18.0-305.19.1.el8_4.x86_64
Architecture: x86-64
[root@CentOS8 ~]#
[root@CentOS8 ~]# exit
logout
Connection to 192.168.192.130 closed.
[root@bobilinux shell]#
如果要登录上百台机器进行操作,传统的方式需要交互操作,显然不够优化
怎么办?
expect 自动应答 tcl语言
安装:
[root@bobilinux shell]# yum -y install expect
[root@bobilinux shell]# rpm -q expect
expect-5.44.1.15-5.el6_4.x86_64
需求1:远程登录到server上什么都不做
脚本:
#!/usr/bin/expect
# 开启一个程序
spawn ssh root@192.168.192.130
# 捕获相关内容
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "1002love\r" }
}
interact //交互
脚本执行方式:
# ./expect1.sh
# /shell04/expect1.sh
# expect -f expect1.sh 非规范执行
执行结果:
[root@bobilinux shell]# vim expect.sh
[root@bobilinux shell]# cat expect.sh
#!/usr/bin/expect
# 开启一个程序
spawn ssh root@192.168.192.130
# 捕获相关内容
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "1002love\r" }
}
interact
[root@bobilinux shell]# chmod +x expect.sh
[root@bobilinux shell]# ./expect.sh
spawn ssh root@192.168.192.130
root@192.168.192.130's password:
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Sat May 7 02:28:10 2022 from 192.168.192.131
[root@CentOS8 ~]#
脚本优化1:
把相关参数定义成变量,实现灵活更改参数
定义变量
#!/usr/bin/expect
set ip 192.168.192.130
set pass 1002love
#定义交互时间
set timeout 5
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
interact
执行结果:
[root@bobilinux shell]# vim expect.sh
[root@bobilinux shell]# cat expect.sh
#!/usr/bin/expect
set ip 192.168.192.130
set pass 1002love
#定义交互时间
set timeout 5
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
interact
[root@bobilinux shell]# expect -f expect.sh
spawn ssh root@192.168.192.130
root@192.168.192.130's password:
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Sat May 7 02:39:23 2022 from 192.168.192.131
[root@CentOS8 ~]#
脚本优化2:
不定义变量,具体参数由用户手动输入
使用位置参数
#!/usr/bin/expect
set ip [ lindex $argv 0 ]
set pass [ lindex $argv 1 ]
set timeout 5
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
interact
执行结果:
[root@bobilinux shell]# vim expect.sh
[root@bobilinux shell]# cat expect.sh
#!/usr/bin/expect
set ip [ lindex $argv 0 ]
set pass [ lindex $argv 1 ]
set timeout 5
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
interact
[root@bobilinux shell]# ./expect.sh 192.168.192.130 1002love
spawn ssh root@192.168.192.130
root@192.168.192.130's password:
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Sat May 7 02:47:50 2022 from 192.168.192.131
[root@CentOS8 ~]#
需求2:远程登录到server上操作
脚本:
#!/usr/bin/expect
set ip 192.168.192.130
set pass 1002love
set timeout 5
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect "#"
#非交互输命令
send "rm -rf /tmp/*\r"
send "touch /tmp/file{1..3}\r"
send "date\r"
send "exit\r"
#程序结束符
expect eof
执行结果:
[root@bobilinux shell]# vim expect.sh
[root@bobilinux shell]# cat expect.sh
#!/usr/bin/expect
set ip 192.168.192.130
set pass 1002love
set timeout 5
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect "#"
#非交互输命令
send "rm -rf /tmp/*\r"
send "touch /tmp/file{1..3}\r"
send "date\r"
send "exit\r"
#程序结束符
expect eof
[root@bobilinux shell]# ./expect.sh
spawn ssh root@192.168.192.130
root@192.168.192.130's password:
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Sat May 7 02:53:39 2022 from 192.168.192.131
[root@CentOS8 ~]# rm -rf /tmp/*
[root@CentOS8 ~]# touch /tmp/file{1..3}
[root@CentOS8 ~]# date
Sat May 7 03:05:02 EDT 2022
[root@CentOS8 ~]# exit
logout
Connection to 192.168.192.130 closed.
[root@bobilinux shell]#
验证:
server上的/tmp/执行前:
[root@CentOS8 admin]# cd /tmp/
[root@CentOS8 tmp]# ls
systemd-private-862b74a5b38b4425973ddaa7225f6e2e-bluetooth.service-oOBUYf
systemd-private-862b74a5b38b4425973ddaa7225f6e2e-chronyd.service-jPLLzf
systemd-private-862b74a5b38b4425973ddaa7225f6e2e-colord.service-NucOPf
systemd-private-862b74a5b38b4425973ddaa7225f6e2e-fwupd.service-gYNVji
systemd-private-862b74a5b38b4425973ddaa7225f6e2e-geoclue.service-r4yQei
systemd-private-862b74a5b38b4425973ddaa7225f6e2e-ModemManager.service-ZLtL9i
systemd-private-862b74a5b38b4425973ddaa7225f6e2e-rtkit-daemon.service-g6qvWe
systemd-private-862b74a5b38b4425973ddaa7225f6e2e-systemd-hostnamed.service-1qeegg
tracker-extract-files.1000
vmware-root_949-4021784396
执行后:
[root@CentOS8 tmp]# ls
file1 file2 file3
需求3:shell脚本和expect结合使用,在多台服务器上创建1个用户
思路:
1. 循环
2. 登录远程主机——>ssh——>从ip.txt文件里获取IP和密码分别赋值给两个变量
3. 使用expect程序来解决交互问题
[root@server shell04]# cat ip.txt
192.168.192.130 1002love
192.168.192.131 1002love
循环按行读取文件内容赋值给变量:
while read ip pass;do ... done < ip.txt (文件如果不是在运行脚本的路径下,需要写绝对路径)
[root@bobilinux shell]# /usr/bin/expect
expect1.1>
expect1.1>
expect1.1> ^C[root@bobilinux shell]#
[root@bobilinux shell]# /usr/bin/expect <<-END
>
> END
[root@bobilinux shell]#
脚本:
#!/bin/bash
# 循环在指定的服务器上创建用户和文件
while read ip pass
do
/usr/bin/expect <<-END &>/dev/null
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect "#" { send "useradd yy1;rm -rf /tmp/*;exit\r" }
expect eof
END
done < ip.txt
执行结果:
[root@bobi shell]# vim ip.txt
[root@bobi shell]# cat ip.txt
192.168.192.130 1002love
192.168.192.131 1002love
[root@bobi shell]# vim expect.sh
[root@bobi shell]# cat expect.sh
#!/bin/bash
# 循环在指定的服务器上创建用户和文件
while read ip pass
do
/usr/bin/expect <<-END &>/dev/null
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect "#" { send "useradd yy1;rm -rf /tmp/*;exit\r" }
expect eof
END
done < ip.txt
[root@bobi shell]#
[root@bobi shell]# chmod +x expect.sh
[root@bobi shell]# ./expect.sh
验证:
192.168.192.130主机:
[root@CentOS8 tmp]# id yy1
uid=1001(yy1) gid=1001(yy1) 组=1001(yy1)
[root@CentOS8 tmp]# ll
总用量 0
192.168.192.131主机:
[root@bobilinux shell]# id yy1
uid=827(yy1) gid=827(yy1) groups=827(yy1)
[root@bobilinux shell]# cd /tmp/
[root@bobilinux tmp]# ll
total 0
排错:
一开始循环死活等不进去第二台主机,但是单独登录第二台就会成功,后来换了第二台机器,还是一样的问题,然后在第二台机器上也安装了 expect ,又成功了
脚本优化:
并行执行
#!/bin/bash
while read ip pass
do
{
/usr/bin/expect <<-HOU
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect "#"
send "hostname\r"
send "exit\r"
expect eof
HOU
}&
done<ip.txt
wait
echo "user is ok...."
或者
#!/bin/bash
cat ip.txt|while read ip pass
do
{
/usr/bin/expect <<-HOU
spawn ssh root@$ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect "#"
send "hostname\r"
send "exit\r"
expect eof
HOU
}&
done
wait
echo "user is ok...."
综合案例1
写一个脚本,将跳板机上yunwei用户的公钥推送到局域网内可以ping通的所
有机器上(推送后,以后ssh登录就不用输密码了)
说明:主机和密码文件已经提供
192.168.192.130: 1002love
192.168.192.131:1002love
案例分析
关闭防火墙和selinux
判断ssh服务是否开启(默认ok)
循环判断给定密码文件里的哪些IP是可以ping通 ip pass
判断IP是否可以ping通——>$?—>流程控制语句
密码文件里获取主机的IP和密码保存变量 ip pass
判断公钥是否存在—>不存在创建它
ssh-copy-id 将跳板机上的yunwei用户的公钥推送到远程主机—>expect解决交互
将ping通的主机IP单独保存到一个文件
测试验证
代码拆分
1.判断yunwei用户的公钥是否存在
[ ! -f /home/yunwei/.ssh/id_rsa ] && ssh-keygen -P '' -f ./id_rsa
2.获取IP并且判断是否可以ping通
1)主机密码文件ip.txt
192.168.192.130:1002love
192.168.192.131:1002love
2) 循环判断主机是否ping通
tr ':' ' ' < ip.txt|while read ip pass
或者
tr ':' ' ' < ip.txt >ip.bak
cat ip.bak|while read ip pass
do
ping -c1 $ip &>/dev/null
if [ $? -eq 0 ];then
判断公钥是否存在
推送公钥
fi
done
3.非交互式推送公钥
/usr/bin/expect <<-END &>/dev/null
spawn ssh-copy-id root@$ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect eof
END
环境准备
1、在跳板机上准备 ip.txt 文件
[root@bobi shell]# cat ip.txt
192.168.192.130:1002love
192.168.192.131:1002love
2、在跳板机上创建yunwei用户
[root@bobi shell]# useradd yunwei
3、由于是新创建的用户,还没有 ssh 登录过,所以没有 .ssh/ 目录,由于该目录权限的特殊性(rwx------)
这里先 ssh 登录一下来自动创建该目录
[root@bobi shell]# su - yunwei
[yunwei@bobi ~]$ ssh 192.168.192.130
The authenticity of host '192.168.192.130 (192.168.192.130)' can't be established.
ECDSA key fingerprint is SHA256:sPUOSErOypZM/9cC541nSFHkPahmRgV+f1XQP3ke+go.
ECDSA key fingerprint is MD5:f7:cd:ea:35:02:2f:31:ad:67:55:3a:7c:46:e9:ee:19.
Are you sure you want to continue connecting (yes/no)? ^C
[yunwei@bobi ~]$ ll -d .ssh/
drwx------ 2 yunwei yunwei 6 May 7 17:29 .ssh/
4、要判断用户的公钥是否存在,需要知道用户创建公钥的具体过程
由于是新用户,还没有公钥
[yunwei@bobi ~]$ cd .ssh/
[yunwei@bobi .ssh]$ ll
total 0
这里,为新用户创建公钥
[yunwei@bobi .ssh]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/yunwei/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/yunwei/.ssh/id_rsa.
Your public key has been saved in /home/yunwei/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:+ajbgaqGcFaIZ52AqbNq8Yth7d9jas40Q5f43hfWnsI yunwei@bobi
The key's randomart image is:
+---[RSA 2048]----+
| o |
|o . |
|.. + . |
|+ + + . .. |
| = . o oS . |
|o.+ . o. o o . |
|o*o. +..o + o . |
|+.=.oo==.. E o |
|.o.+*==+o.. . |
+----[SHA256]-----+
[yunwei@bobi .ssh]$
[yunwei@bobi .ssh]$ ll
total 8
-rw------- 1 yunwei yunwei 1675 May 7 17:36 id_rsa
-rw-r--r-- 1 yunwei yunwei 393 May 7 17:36 id_rsa.pub
创建完成后,可以看到 .ssh/ 目录下生成了两个文件,可以根据这两个文件是否存在去判断用户的公钥是否存在
5、上述的创建公钥的过程是交互的,需要优化为非交互的创建公钥:
[yunwei@bobi .ssh]$ rm -fr *
[yunwei@bobi .ssh]$ ll
total 0
[yunwei@bobi .ssh]$ ssh-keygen -P '' -f ~/.ssh/id_rsa
Generating public/private rsa key pair.
Your identification has been saved in ./id_rsa.
Your public key has been saved in ./id_rsa.pub.
The key fingerprint is:
SHA256:axpi07Arl599VcuB1h2LhUMg+H65SDMW1uQSRqD5NOE yunwei@bobi
The key's randomart image is:
+---[RSA 2048]----+
| o+o .o.. |
| +..o.. o o |
| o Eo = o+.o|
| o .= oo.+..|
| . .S o..o o |
| + B o. o |
| =.o = =.. |
| ..o+ * ... |
| o..+ .. |
+----[SHA256]-----+
[yunwei@bobi .ssh]$ ll
total 8
-rw------- 1 yunwei yunwei 1679 May 7 17:44 id_rsa
-rw-r--r-- 1 yunwei yunwei 393 May 7 17:44 id_rsa.pub
6、要想实现非交互推送公钥需要知道推送公钥的具体过程:
[yunwei@bobi .ssh]$ ssh-copy-id root@192.168.192.130
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/yunwei/.ssh/id_rsa.pub"
The authenticity of host '192.168.192.130 (192.168.192.130)' can't be established.
ECDSA key fingerprint is SHA256:sPUOSErOypZM/9cC541nSFHkPahmRgV+f1XQP3ke+go.
ECDSA key fingerprint is MD5:f7:cd:ea:35:02:2f:31:ad:67:55:3a:7c:46:e9:ee:19.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.192.130's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.192.130'"
and check to make sure that only the key(s) you wanted were added.
[yunwei@bobi .ssh]$
接下来以非交互式推送替代交互式推送:
/usr/bin/expect <<-END &>/dev/null
spawn ssh-copy-id root@$ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect eof
END
7、有可能yunwei用户没有安装 expect 软件包,要想实现这个脚本,肯定需要安装,而普通用户不具备这个安装的权限
怎么办
给yunwei用户进行 sudo 授权,让他有 root 的权限,可以通过 sudo 安装 expect 软件包
visudo
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
yunwei ALL=(root) NOPASSWD:ALL,!/sbin/shutdown,!/sbin/init,!/bin/rm -rf /,!/sbin/reboot
解释说明:
1)第一个字段yunwei指定的是用户:可以是用户名,也可以是别名。每个用户设置一行,多个用户设置多行,也可以将多个用户设置成一个别名后再进行设置。
2)第二个字段ALL指定的是用户所在的主机:可以是ip,也可以是主机名,表示该sudo设置只在该主机上生效,ALL表示在所有主机上都生效!限制的一般都是本机,也就是限制使用这个文件的主机;一般都指定为"ALL"表示所有的主机,不管文件拷到那里都可以用。比如:10.1.1.1=...则表示只在当前主机生效。
3)第三个字段(root)括号里指定的也是用户:指定以什么用户身份执行sudo,即使用sudo后可以享有所有root账号下的权限。如果要排除个别用户,可以在括号内设置,比如ALL=(ALL,!oracle,!pos)。
4)第四个字段ALL指定的是执行的命令:即使用sudo后可以执行所有的命令。除了关机和删除根内容以外;也可以设置别名。NOPASSWD: ALL表示使用sudo的不需要输入密码。
5)也可以授权给一个用户组
%admin ALL=(ALL) ALL 表示admin组里的所有成员可以在任何主机上以任何用户身份执行任何命令
最终实现——脚本
#!/bin/bash
#循环判断主机是否ping通,如果ping通推送公钥
tr ':' ' ' < /tmp/shell/ip.txt|while read ip pass
do
{
ping -c1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo $ip >> /tmp/shell/ip_up.txt
[ ! -f /home/yunwei/.ssh/id_rsa ] && ssh-keygen -P '' -f ~/.ssh/id_rsa
/usr/bin/expect <<-END &>/dev/null
spawn ssh-copy-id root@$ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect eof
END
fi
}&
done
wait
echo "公钥已经推送完毕,请通过 ssh root@remote_ip 测试...."
测试验证
在多次验证的过程,上面的代码有时成功有时失败。。。
运行脚本前:
192.168.192.130:
[root@CentOS8 .ssh]# ll
总用量 0
192.168.192.131:
[root@bobilinux .ssh]# ll
total 4
-rw-r--r-- 1 root root 2173 May 7 15:53 known_hosts
运行脚本:
[yunwei@bobi shell]$ sudo vim ssh_public.sh
[yunwei@bobi shell]$ sudo cat ssh_public.sh
#!/bin/bash
#循环判断主机是否ping通,如果ping通推送公钥
tr ':' ' ' < /tmp/shell/ip.txt|while read ip pass
do
{
ping -c1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo $ip >> /tmp/shell/ip_up.txt
[ ! -f /home/yunwei/.ssh/id_rsa ] && ssh-keygen -P '' -f ~/.ssh/id_rsa
/usr/bin/expect <<-END &>/dev/null
spawn ssh-copy-id root@$ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect eof
END
fi
}&
done
wait
echo "公钥已经推送完毕,请通过 ssh root@remote_ip 测试...."
[yunwei@bobi shell]$ sudo chmod +x ssh_public.sh
[yunwei@bobi shell]$ sudo ./ssh_public.sh
公钥已经推送完毕,请通过 ssh root@remote_ip 测试....
[yunwei@bobi shell]$
[yunwei@bobi shell]$ ssh root@192.168.192.131
Last login: Sat May 7 19:36:16 2022 from 192.168.192.145
[root@bobilinux ~]#
[root@bobilinux ~]# exit
logout
Connection to 192.168.192.131 closed.
[yunwei@bobi shell]$
[yunwei@bobi shell]$ ssh root@192.168.192.130
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Sat May 7 07:34:01 2022 from 192.168.192.145
[root@CentOS8 ~]#
[root@CentOS8 ~]# exit
logout
Connection to 192.168.192.130 closed.
[yunwei@bobi shell]$
运行脚本后:
192.168.192.130:
[root@CentOS8 .ssh]# ll
总用量 4
-rw-------. 1 root root 393 5月 7 07:48 authorized_keys
192.168.192.131:
[root@bobilinux .ssh]# ll
total 8
-rw------- 1 root root 393 May 7 19:48 authorized_keys
-rw-r--r-- 1 root root 2173 May 7 15:53 known_hosts
综合案例2
写一个脚本,统计web服务的不同连接状态个数:
案例分析
1、首先要知道如何查看服务的状态,有两个命令
netstat
[--listening|-l] [--numeric|-n] [--tcp|-t] [--udp|-u] [--program|-p]
[--all|-a] [--numeric|-n] [--program|-p]
ss
-n, --numeric -a, --all -l, --listening -t, --tcp -u, --udp
有三种命令可供使用:
命令一:
[root@bobilinux ~]# netstat -anp
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:875 0.0.0.0:* LISTEN 1020/rpc.rquotad
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 955/rpcbind
命令二:
[root@bobilinux ~]# netstat -lntup
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:875 0.0.0.0:* LISTEN 1020/rpc.rquotad
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 955/rpcbind
命令三:
[root@bobilinux ~]# ss -an
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:875 *:*
LISTEN 0 128 :::111 :::*
要统计不同连接状态的个数,需要把上面的信息里面的 state 列取出来进行统计
显然,使用 ss -an 命令后的信息更容易取 state 列
ss -ant|grep 80|cut -d' ' -f1
2、取出 state 列后,对该列下的不同状态进行统计
[root@bobilinux shell]# cat states.txt
LISIEN
LISTEN
SYN-RECV
ESTAB
SYN-RECV
LISIEN
ESTAB
ESTAB
SYN-RECV
可以先使用 sort 命令进行排序,再使用 uniq -c 去统计重复行的数量,以此来统计不同连接状态的个数
ss -ant|grep 80|cut -d' ' -f1|sort|uniq -c
[root@bobilinux shell]# cat states.txt|sort
ESTAB
ESTAB
ESTAB
LISIEN
LISIEN
LISTEN
SYN-RECV
SYN-RECV
SYN-RECV
[root@bobilinux shell]# cat states.txt|sort|uniq -c
3 ESTAB
2 LISIEN
1 LISTEN
3 SYN-RECV
也可以将使用关联数组,将连接状态作为关联数组的下标,去统计关联数组的元素个数
[root@bobilinux shell]# declare -A array1
[root@bobilinux shell]# states=`cat states.txt`
[root@bobilinux shell]# for i in $states;do let array1[$i]++;done
[root@bobilinux shell]# for j in ${!array1[@]};do echo $j:${array1[$j]};done
ESTAB:3
SYN-RECV:3
LISIEN:2
LISTEN:1
脚本实现
#!/bin/bash
#count_http_80_state
#定义关联数组
declare -A array1
states=`ss -ant|grep 80|cut -d' ' -f1`
#统计每个状态的个数
for i in $states
do
let array1[$i]++
done
#通过遍历数组里的索引和元素打印出来
for j in ${!array1[@]}
do
echo $j:${array1[$j]}
done