#!/usr/bin/python2 # # nbcalc is a netblock calculator: you give it netblocks or facsimiles # thereof, it adds (or subtracts) them together, and finishes off by # spitting out the resulting netblock(s). import sys sys.path.insert(1, "/u/cks/share/python") # look ma, netblock caculations: import netblock def die(str): sys.stderr.write(sys.argv[0] + ': ' + str + '\n') sys.exit(1) def warn(str): sys.stderr.write(sys.argv[0] + ': ' + str + '\n') def dumpout(r): res = r.tocidr() if len(res) > 0: print "\n".join(res) def process(args): r = netblock.IPRanges() # people's republic of glorious special cases. if len(args) == 3 and args[1] == "-": process(["%s-%s" % (args[0], args[2]),]) return # We permit the rarely used calculator mode. opd = r.add for a in args: op = opd # Are we changing the operation? if a == "-": opd = r.remove continue elif a == "+": opd = r.add continue # We might be asking for a one-shot subtraction. if a[0] == '-': op = r.remove a = a[1:] # We notice bad input by the errors that netblock throws. try: op(a) except netblock.BadCIDRError, e: # Because this happens SO OFTEN, give a specific # message. c = netblock.convcidr(a, 0) die("bad CIDR %s. Should start at IP %s" % \ (a, netblock.ipstr(c[0]))) except netblock.NBError, e: die("bad argument %s: %s" % (a, str(e))) dumpout(r) #import profile if __name__ == "__main__": #profile.run('process(sys.argv[1:])') process(sys.argv[1:])