Pages

Saturday, December 12, 2015

Sample script to extract virtual host from httpd.conf file of Apache


Requirement:-

A simple script to extract each virtual host defined in an apache configuration file to separate files.

Inputs:-

Apache file absolute path is the only input required for the script.

Outputs:-

Separate files starting with name virtualhost* would be generated in same folder from where script is being executed.

Script:-

#####
#!/bin/bash
# Variable Initialization
FILEPATH=$1
COUNTER=0
#####
if [ $# -eq 1 ]
then
  if [ -f $FILEPATH ]
  then
    # Read Virtualhosts file line by line
    for LINE in $(cat $FILEPATH |grep -v '#' |sed -n '/<VirtualHost/,/<\/VirtualHost/p' |sed '/<\/VirtualHost/ a --------'|tr '\n' '^' |sed 's/\^--------\^/\n/g'| tr ' ' '@' )
    do
      # Extract each virtualhost in seperate file
      echo $LINE| tr '@' ' ' |tr '^' '\n' > virtualhost_$COUNTER.txt
      # Increment Counter for using in next virtualhost out filename
      let COUNTER=$COUNTER+1
    done
  else
    echo "Input file $FILEPATH missing / does not exist"
  fi
else
  echo "Usage: $0 'INPUT VHOST FILE'"
fi
#####


Script is very basic and subject to additional error depending on environment, make sure necessary alternations are made to get it used in any environment.


References :-
https://gist.github.com/lavoiesl/2629830

No comments:

Post a Comment