一些 Shell 练习

【一些 Shell 练习】行是知之始,知是行之成。这篇文章主要讲述一些 Shell 练习相关的知识,希望能为你提供帮助。


  1. 编写脚本实现登陆远程主机。(使用 expect 和 shell 脚本两种形式)。
  • expect 形式
[root@Redis-m1:~]#vim expect2.sh
#!/usr/bin/expect
set HOST [lindex $argv 0]
set USER [lindex $argv 1]
set PASSWORD [lindex $argv 2]
spawn ssh $USER@$HOST
expect
"yes/no"send "yes\\n"; exp_continue
"password"send "$PASSWORD\\n"

interact

[root@Redis-m1:~]#./expect2.sh 192.168.68.71 root cnhope
spawn ssh root@192.168.68.71
The authenticity of host 192.168.68.71 (192.168.68.71) cant be established.
ECDSA key fingerprint is SHA256:J22pOZ72CGabJHprnwnSFZ6ZHBYuqHKj4avo6PEcaSI.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 192.168.68.71 (ECDSA) to the list of known hosts.
root@192.168.68.71s password:
Last login: Tue Feb8 01:23:05 2022 from 192.168.68.21
[root@centos7.9-68.7 ~]#
[root@centos7.9-68.7 ~]#
[root@centos7.9-68.7 ~]#exit

  • shell 形式
[root@Redis-m1:~]#vim expect.sh
#!/bin/bash
HOST=$1
USER=$2
PASSWORD=$3
expect < < EOF
spawn ssh $USER@$HOST
expect
"yes/no"send "yes\\n"; exp_continue
"password"send "$PASSWORD\\n"

expect "]#"send "ip a\\n"
expect "]#"send "exit\\n"
expect eof
EOF

[root@Redis-m1:~]#./expect.sh 192.168.68.71 root cnhope
spawn ssh root@192.168.68.71
root@192.168.68.71s password:
Last login: Tue Feb8 01:40:33 2022 from 192.168.68.21
[root@centos7.9-68.7 ~]#ip a
1: lo: < LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: < BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:3f:4d:b3 brd ff:ff:ff:ff:ff:ff
inet 192.168.68.71/24 brd 192.168.68.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::1bc5:53cc:1425:63e7/64 scope link noprefixroute
valid_lft forever preferred_lft forever
[root@centos7.9-68.7 ~]#exit
logout
Connection to 192.168.68.71 closed.




  1. 生成10个随机数保存于数组中,并找出其最大值和最小值
  2. 输入若干个数值存入数组中,采用冒泡算法进行升序或降序排序
  3. 总结查看系统负载的几种命令,总结top命令的指标大概什么含义(不要求全部写出来)

  4. 编写脚本,使用for和while分别实现192.168.0.0/24网段内,地址是否能够ping通,若ping通则输出"success!",若ping不通则输出"fail!"
[root@ubuntu]#cat ping-check1.sh
#!/bin/bash
for (( i=1; i< =254; i++ )); do

ping -c1 -W1 192.168.0.$i > & /dev/null
if [ $? -eq 0 ]; then
echo 192.168.0.$i is success!
else
echo 192.168.0.$i is fail!
fi
&
done
wait

  1. 每周的工作日1:30,将/etc备份至/backup目录中,保存的文件名称格式 为“etcbak-yyyy-mm-dd-HH.tar.xz”,其中日期是前一天的时间。
#1.创建备份脚本
[root@ubuntu]#vim /root/backup.sh
#!/bin/bash
if [ -d /backup ]; then
sleep 1
else
mkdir /backup
fi
tar -Jcvf /backup/etcbak-`date -d "-1 day" "+%F-%H"`.tar.xz /etc

#2.创建计划任务
[root@ubuntu]#crontab -e
30 1 1-5 * * /bin/bash /root/backup.sh




    推荐阅读