2、在钩子中调用shell脚本,由shell脚本实现向hosts中增加域名。方案如下:
#!/bin/bash #hosts="`sed -n 's/ServerName\s\+\(.\+\)/127.0.0.1 \1/p' httpd.conf|sed 's/\<www\.//p'`" #\1是反向引用,-n表示静默模式,s指令表示替换匹配,p表示打印匹配项。 #此方法弃用是因为过滤的结果中多了一些重复行,原因是p命令会在每次的循环处理之后再隐式地输出一次。 #要避免此问题,可以加上静默模式,即-n, 所以上面的指令可以这么写: #hosts="`sed -n 's/ServerName\s\+\(.\+\)/127.0.0.1 \1/p' httpd.conf|sed -n 's/\<www\.//p'`" hosts="`sed -n -e'/^#.*/d' -e's/\<www\.//' -e's/ServerName\s\+\(.\+\)/\1/p' $1`" #从httpd.conf中找出配置的域名, #其中$1是bash脚本的输入参数,在这里即是文件httpd.conf的路径。 changed='' for host in $hosts do # sed '/^#.*/d'是为了过滤掉注释行(d命令表示删除匹配)。grep -i表示不区分大小写,-E表示使用扩展正则而不是基础正则。 found=`sed '/^#.*/d' /etc/hosts|grep -i -E '\s'$host' |\s'$host'$'` #在hosts文件中查找有没有对应的域名 if [[ $found ]] then continue fi changed=1 echo 127.0.0.1 $host www.$host >> /etc/hosts echo 'DocumentRoot "/mnt/pcshare/Flashbay" ServerName www.'$host' ServerAlias '$host' ' >> /etc/httpd/conf.d/vhosts.conf done if [[ $changed ]] then systemctl restart httpd fi