sync-router 2.89 KB
#!/bin/bash -e
#
# sync-router	shell scripts to synchronize cisco configuration and DHCP static
#		lease files with with GIT repository. Operations performed:
#		  - update header of modified DHCP static lease files, upload
#		    them using using scp and add them to the next commit
#		  - restart Cisco DHCP service after updating static lease files
#		  - copy Cisco startup-config using scp and add to next commit
#		  - commit changes to the git repository
#
# Version 1.0, latest version at: https://gitlab.lindenaar.net/scripts/cisco
#
# Copyright (c) 2016 Frederik Lindenaar
#
# This script is free software: you can redistribute and/or modify it under the
# terms of version 3 of the GNU General Public License as published by the Free
# Software Foundation, or (at your option) any later version of the license.
#
# This script is distributed in the hope that it will be useful but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, visit <http://www.gnu.org/licenses/> to download it.

### Configuration ###
router=`basename \`dirname $0 | pwd\``	# name of router - based on directory
syncfiles=dhcp-\*			# list/pattern of dhcp lease files
fileto=flash:				# location of dhcp lease files on cisco

### Implementation ###
echo updating with $router

# Process the DHCP static lease files that have changed
git status -s "$syncfiles" | while read status filename
do
  case $status in
    \?\?)
	echo skipping $filename as it is not yet added to the repository
	;;
    D)
	echo removing  $filename as it is no longer in the repository
	ssh -q $router "delete /force $fileto$filename"
	;;
    A |M)
  	echo updating and uploading modified file $filename
	head -2 $filename | while read tag value
	  do
	    case $tag in
	      \*time\*)
		date +"$tag %h %d %Y %l:%M %p" > .$filename.$$.tmp
		;;
	      \*version\*)
		echo $tag $[ $value + 1 ] >> .$filename.$$.tmp
		;;
	      *)
		echo "found unknown entry \"$tag $value\", aborting"
		exit 1
		;;
	      esac
	  done
	tail +3 $filename >> .$filename.$$.tmp
	scp -q .$filename.$$.tmp $router:$fileto$filename
	mv .$filename.$$.tmp $filename
	git add $filename
	;;
    *)
	echo unsupported git status "$status", aborting
	exit 1
	;;
  esac
done

# Restart the DHCP service on the router if any of the dhcp files changed
if git status -s "$syncfiles" | egrep -q ^[MAD]; then
  echo restarting dhcp service
  cat << EOT | ssh -q $router
configure terminal
no service dhcp
service dhcp
exit
exit
EOT
fi

# Fetch the current start-up configuration and add it to the repository
scp -q $router:startup-config .
git diff startup-config
git add startup-config

# and commit the changes (or unadd new configuration when commit is aborted)
git commit || git reset HEAD startup-config