Linux shell脚本编程基础练习

一、编写脚本/root/bin/systeminfo.sh,显示当前主机系统信息,包括主机名,IPv4地址,操作系统版本,内核版本,CPU型号,内存大小,硬盘大小

第一步

#!/bin/bash

echo "Hostname is `hostname`"
echo "IPv4 address is `ifconfig ens33 | grep -Eo "\<(([1-9]?[0-9]|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\.){3}([1-9]?[0-9]|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\>" | head -n 1`"
echo "OS version is `cat /etc/redhat-release | cut -d " " -f 4`"
echo "Kernel version is `uname -r`"
echo "CPU model is `lscpu | grep "^Model name" | tr -s " " | grep -Eo "[^(Model name: )].*$"`"
echo "Memory total is `free -h | tr -s " " | head -n 2 | tail -n 1 | cut -d " " -f 2`"
echo "Disk total is `lsblk | grep -Eo "^sd.*" | tr -s " " | cut -d " " -f 4`"

第二步

赋予对脚本的执行权限。

chmod +x /root/bin/systeminfo.sh

[root@centos7 ~]#chmod +x /root/bin/systeminfo.sh

第三步

[root@centos7 ~]#systeminfo.sh
Hostname is centos7.kkk
IPv4 address is 192.168.30.139
OS version is 7.4.1708
Kernel version is 3.10.0-693.el7.x86_64
CPU model is Intel(R) Core(TM) i5-3320M CPU @ 2.60GHz
Memory total is 1.0G
Disk total is 200G

 

 

二、编写脚本/root/bin/backup.sh,可实现每日将/etc/目录备份到/root/etcYYYY-mm-dd中

第一步

#!/bin/bash

DATE=`date "+%F"`
`cp -a /etc/ /root/etc"$DATE"`
[ "$?" -eq 0 ] && echo "Done!" || echo "Someting wrong!"

第二步

赋予对脚本的执行权限。

chmod +x /root/bin/backup.sh

[root@centos7 ~]#chmod +x /root/bin/backup.sh

第三步

[root@centos7 ~]#backup.sh
Done!
[root@centos7 ~]#ll -d etc2019-11-10/
drwxr-xr-x. 132 root root 8192 Nov  9 22:32 etc2019-11-10/

 

 

三、编写脚本/root/bin/disk.sh,显示当前硬盘分区中空间利用率最大的值

第一步

#!/bin/bash

echo "Maximum artition utilization rate is `df -h | grep "/dev/sd.*" | tr -s " " % | cut -d % -f 5 | sort -nr | head -n 1`"

第二步

赋予对脚本的执行权限。

chmod +x /root/bin/disk.sh

[root@centos7 ~]#chmod +x /root/bin/disk.sh

第三步

[root@centos7 ~]#disk.sh
Maximum artition utilization rate is 16

 

 

四、编写脚本/root/bin/links.sh,显示正连接本主机的每个远程主机的IPv4地址和连接数,并按连接数从大到小排序

第一步

思路:

由于显示的内容不止一行,如果单纯执行命令echo会把所有内容在一行显示,需要在脚本末尾加上换行符\n,并给命令echo加上参数-e,启用\字符的解释功能。

#!/bin/bash

echo -e "`netstat -nt | tr -s " " | cut -d " " -f 5 | grep -Eo "\<(([1-9]?[0-9]|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\.){3}([1-9]?[0-9]|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\>" | sort | uniq -c | sort -nr`\n"

第二步

赋予对脚本的执行权限。

chmod +x /root/bin/links.sh<

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值