任何人都可以帮助我开发以下脚本吗?
我在/etc/httpd/httpd.conf文件中有以下条目
<VirtualHost 192.168.1.181:80>
DocumentRoot /var/www/html/
ServerName example.com
</VirtualHost>"
如果有人输入了example.com输入,我需要从同一文件/etc/httpd/httpd.conf中完全删除example.com的同一虚拟主机条目。我怎样才能做到这一点 ?
最佳答案
这是一个bash脚本,它将删除包含与该程序的第二个参数提供的VirtualHost
匹配的domain
的任何domain
块。该脚本的用途是:
./scriptname /path/to/httpd.conf somedomain.com
操作很简单。它将读取现有的httpd.conf,在/ tmp中创建一个临时的httpd.conf。它读取httpd.conf以查找任何
VirtualHost
标记,然后将与它们关联的所有行缓冲在数组中。它测试是否在该somedomain.com
块中找到VirtualHost
。如果找到它,则不会写入新文件。如果未找到,则VirtualHost
块的所有行均保持不变。与VirtualHost
块无关的任何其他行都将被简单地写入新文件。解析后,通过diff比较新/旧的httpd.conf文件。如果它们不匹配,则将新的httpd.conf写入系统httpd.conf位置。该脚本在下面进行了注释。如果您还有其他问题,请告诉我:
#!/bin/bash
# this file must be run as root
test "$UID" = 0 || {
printf "\n Error, insufficient privileges. root user required, user '%s' won't work.\n\n" "$USER"
exit 1
}
## declare needed variables and flags
declare -a tmp # temp array to hold lines between <VirtualHost tags
declare -i loop=0 # flag to loop over all line in <VirtualHost blocks
declare -i found=0 # flag indicating domain to delete is found
tmstamp="$(date +%s)" # unique timestamp for backup of httpd.conf
domain="${2:-example.com}" # give domain to find as 2nd arg on command line
htfile="${1:-/etc/httpd/conf/httpd.conf}" # confirm path/filename for your setup
tmpfile="/tmp/httpd.conf.tmp" # temp file to write remaining httpd.conf lines to
:> "$tmpfile" # truncate tmpfile
## backup httpd.conf, exit on err
cp -a "${htfile}" "${htfile}.$tmstamp" || {
printf "\n Error, failed to make backup of httpd.conf.\n\n"
exit 2
}
## NOTE: do not unset IFS, leave at default
# read all lines in httpd.conf
while read -r line || test -n "$line"; do
if test "${line:0:12}" == "<VirtualHost" || test $loop -eq 1 ; then # if <VirtualHost found
loop=1 # set loop flag to 1 to continue looping
tmp+=( "$line" ) # while looping add each line to tmp array
test "${line##* }" == "$domain" && found=1 # if wanted domain found, set found flag=1
if test "$line" == "</VirtualHost>" ; then # if closing </VirtualHost tag found
loop=0 # reset loop to 0
if test "$found" -eq 1 ; then # if 'found', just reset found flag (don't write)
found=0
else # otherwise, write the VirtualHost block to file`
for ((i=0; i<${#tmp[@]}; i++)); do
printf "%s\n" "${tmp[$i]}" >> "$tmpfile"
done
fi
unset tmp # lastly - unset tmp array
fi
else # Not in VirtualHost block, so
printf "%s\n" "$line" >> "$tmpfile" # output all non-interesting lines to tmpfile
fi
done <"$htfile"
## if new and old httpd.conf files differ, copy new to old
diff -qw &>/dev/null "$htfile" "$tmpfile" || cp -a "$tmpfile" "$htfile"
rm "$tmpfile" # remove tmpfile
exit 0
关于linux - 用于删除文件中单词的Shell脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25883318/