随机数

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. 10001000
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
#!/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
[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 56 22:57 phonenum.txt
-rwxr-xr-x. 1 root root 305 56 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
334 ${变量值:下标:长度}
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 使12使 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.txtIP
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)
IPping ip pass
IPping>$?>
IP ip pass
>
ssh-copy-id yunwei>expect
pingIP

代码拆分

1.yunwei
[ ! -f /home/yunwei/.ssh/id_rsa ] && ssh-keygen -P '' -f ./id_rsa


2.IPping
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


2yunwei
[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


7yunwei 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)ALLip,sudoALL使;"ALL"10.1.1.1=...
3)(root)sudo使sudorootALL=(ALL,!oracle,!pos)
4)ALL使sudoNOPASSWD: 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

shell编程之嵌套循环+随机数及综合案例_批量设置随机密码

shell编程之嵌套循环+随机数及综合案例_expect非交互_02

脚本实现

#!/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