1

I want to create about a dozen or-so python scripts that will talk to network devices, most of them will do some sort of telnet/ssh/snmp action, either getting info or modifying it.

In perl I normally would use a nested hash which works ok, tried to re-write this to a nested dictionary in python and this works.... but I'm not sure if I should use classes or not. Basically the most important data structures that I need are things:

  • "workunit", basically a device with a number of properties like ipaddress, hostname, log_file_locations, results etc..

  • "settings" and "transport" dictionary which basically says are we doing ssh or snmp and what are the settings for it (userid/password, community string etc..)

So if I run a script for example for 10 devices, then I will normally have a dictionary of dictionaries with the ipaddress as a key to that dict.

I could also of course create a "Workunit" class, and create a basic list of "Workunit" objects, but the more I read about python the less "pythonic?" it feels... Any insight to what the "right" approach is in this case? (both will work I'm sure).

ldgorman
  • 1,553
  • 1
  • 14
  • 39
Justin
  • 23
  • 5

1 Answers1

1

It's ultimately up to you. If you want to make your code more re-usable, then take the time to implement the functionality under OOP. Since you are planning on creating 12 or so scripts it may be worthwhile. The structure you have described could be created in a library that your scripts can each reference.

In terms of implementing a dictionary with a custom data type in python, you just need to implement a few required methods

class MyThing:
def __init__(self,name,location,length):
    self.name = name
    self.location = location
    self.length = length

def __hash__(self):
    return hash((self.name, self.location))

def __eq__(self, other):
    return (self.name, self.location) == (other.name, other.location)

def __ne__(self, other):
ldgorman
  • 1,553
  • 1
  • 14
  • 39