前言
Shell脚本编程的灵活运用需要有对脚本基础,不同的语句组合应用具有十分熟悉的理解。接下来就通过一些实际项目来更加深刻的体会Shell在生活中的应用。
步骤
- 需求分析:根据系统管理的需求,分析脚本要实现的功能,功能实现的层次,实现的命令与语句等
- 命令测试:将要用到的命令逐个进行测试,以决定使用的选项,要设置的变量等
- 脚本编程:将测试好的命令写入到脚本文件中,并通过各种语句将命令执行的结果保存,判断或者发出报警等
- 测试调优:对脚本进行测试,并根据结果进行优化建议一边编程一边调试,以减少错误的发生
项目实战:
1.实现ssh的免密登录。
#!/bin/bash
# 实现ssh的免密登录。
yum -y install expect
CLIENT1=$1
USER=$2
PASSWD=$3
expect << -EOF
spawn ssh-keygen -t rsa
expect {
"save the key" {send "\r";exp_continue}
"Overwrite" {send "y\r";exp_continue}
"Enter passphrase" {send "\r";exp_continue}
"same passphrase" {send "\r"}
}
spawn ssh-copy-id ${USER}@${CLIENT1}
expect {
"yes/no" {send "yes\r";exp_continue}
"password" {send "$PASSWD\r"}
}
expect eof
-EOF
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@20.0.0.13'"
and check to make sure that only the key(s) you wanted were added.
[root@server1 ~]# ssh root@20.0.0.13
Last login: Tue Nov 17 20:02:33 2020 from 20.0.0.1
[root@server1 ~]# exit
登出
Connection to 20.0.0.13 closed.
2.实现dns及apache服务的一键化部署,要求apche服务器绑定域名,客户机实现访问。
dns_zones=/etc/named.rfc1912.zones
local=/var/named/lzw.com.local
zone=/var/named/lzw.com.zone
yum -y install httpd
yum -y install bind*
[ -e /var/www/html/index.html ] || touch /var/www/html/index.html
index=/var/www/html/index.html
cat /root/index.html.txt > $index
sed -i '/port/s/{.*}/{ 20.0.0.13; }/' $dns_conf
sed -i '/allow-query/s/{.*}/{ any; }/' $dns_conf
cat /root/named_zones.txt >> $dns_zones
cp -p $dns/named.localhost $dns/lzw.com.local
cp -p $dns/named.loopback $dns/lzw.com.zone
chown $dns/root:named $dns/lzw.com.zone
chown $dns/root:named $dns/lzw.com.local
cat /root/local.txt > $local
cat /root/zone.txt > $zone
sed -i '1anameserver 20.0.0.13' /etc/resolv.conf
sed -i '1{H;d};2G' /etc/resolv.conf
systemctl restart named.service
systemctl status named.service
systemctl restart httpd
systemctl status httpd
nslookup www.lzw.com