clear ip nat selectively

On cisco router device you can clear all ip nat translations once doing:

:::bash
Router#clear ip nat translation *

but when you try remove only one translation you have to write long command i.e.

:::bash
Router#clear ip nat translation udp inside <ip> <port> <ip> <port> outside <ip> <port> <ip> <port>

which also cannot be easy cut and past from show command result. Fortunetly in cisco device there is a TCL shell, activated by:

:::bash
Router#tclsh

Sample script to clear ip nat selectively:

:::bash
proc clearnat {x} {
set result [exec {sh ip nat translation}]
set data [split $result "\n"]

foreach item $data {

    if {[string match *$x* $item]} {
	set wordList [regexp -all -inline {\S+} $item]
	set proto [ lindex $wordList 0 ]
	set insglob [ lindex $wordList 1 ]
	regsub -all ":" $insglob " " insglob
	set inslocal [ lindex $wordList 2 ]
	regsub -all ":" $inslocal " " inslocal
	set outlocal [ lindex $wordList 3 ]
	regsub -all ":" $outlocal " " outlocal
	set outglob [ lindex $wordList 4 ]
	regsub -all ":" $outglob " " outglob
	clear ip nat translation $proto inside $insglob $inslocal outside $outlocal $outglob
    }

}

}

Paste it in tclsh and fire up with:

:::bash
Router(tcl)#clearnat <ip>

For me it was first met of tcl scripting, so it isn’t written optimally. TCL script looks pretty odd to my previous scripting experience ;)

comments powered by Disqus

powered by Hugo and Noteworthy theme