Automatically Creating Initial_data fixtures for Sites.Site

This is an ultra-hacky way to create initial_data fixtures for django admin's Sites.site.  Create a variable in settings.py such as "FQDN" then create a dictionary with all the values and wrap it with a list, import json and dump the list into json and write it to app_name/fixtures/initial_data.json


settings.py:

#ADD your own variable
FQDN="www.whateversite.com"
full_path = 'path/to/project/project_name/app_name/fixtures/initial_data.json'
print full_path

try:
   with open(full_path) as f: pass
except IOError as e:
   print str(e)
   site_fixture_dict = {}
   site_fixture_dict['pk']=1
   site_fixture_dict['model']="sites.site"
   site_fixture_dict['fields']={'name':FQDN,'domain':FQDN}
   site_fixture_list = [site_fixture_dict]
   import json
   json = json.dumps(site_fixture_list)
   f = open(full_path,'w')
   f.write(json)
   f.close()

Now any time you run ./manage.py syncdb a fixture will be created then loaded into the database

Tagged as django , fixtures settings.py , site sites.site
Written by Andrew Konkol on August 1st, 2012 | 0 Comments

Spur - Network Configuration Manager

I've been developing a web front-end for tratto.  This front end is called spur and allows you to run commands on any ssh/telnet available device and store the outputs.

  • Web configured cron jobs
  • Any command set
  • Define your own operating systems
  • Run diff's on command outputs
  • Since you can run any command you can do things like backup configurations from cisco routers and switches
  • Get alerts on outputs, diffs, and failures
  • Synatx highlighting

I'm looking to release this for free via github in the near future.  Meanwhile here are some screenshots:

 

 

 

Tagged as cisco , ncm pexpect , spur ssh , telnet
Written by Andrew Konkol on July 30th, 2012 | 0 Comments

Turning a dictionary into a Tuple for Django flat_choices

Here is my pre-defined code called "Systems.py" as you can see I create a dictionary at the end of this to link display names to classes. This code is part of the meat-and-potatoes of my web app and instead of creating a model for these I want them to be defined in the actual code. I don't want to access the database every time I need to reference these and I also want this code to be portable in the means that you can use it in a shell as well as the web app.

class OperatingSystem(object):
        ESCALATE_COMMAND=''
        PAGINATES       =False
        VERSION         =''
        PROMPTLINE      =''



class CiscoIOS(OperatingSystem):
        '''cisco ios'''
        PROMPTLINE      = r'[-\w]+[>#]'
        GET_CONFIG      ='show running-config'
        PAGINATES       =True
        VERSION         ='show version'
        DISABLE_PAGINATION = 'terminal length 0'
        ESCALATE_COMMAND='enable'

class CiscoWebNS(OperatingSystem):
        '''cisco webns css 11500'''
        PROMPTLINE      ="#"
        GET_CONFIG      ='show running config'
        PAGINATES       =True
        DISABLE_PAGINATION = 'terminal length 65000'

class AppleOSX(OperatingSystem):
        '''apple OSX defaults'''
        PROMPTLINE      = r'[-\w]+[$#]'
        VERSION         ="uname -a"
        PRIVILEGE       ="sudo su"

class OpenBSD(OperatingSystem):
        '''OpenBSD defaults'''
        PROMPTLINE      = r'[$#]'
        VERSION         ="uname -a"
        PRIVILEGE       ="sudo su"


class SecureComputingSidewinder(OperatingSystem):
        '''sidewinder configs'''
        PROMPTLINE      ='{}'
        PRIVILEGE       ='srole'
        GET_CONFIG      ="cf acl query"

class ArubaOS(OperatingSystem):
        '''aruba configs'''
        PROMPTLINE      ='#'
        PAGINATES       =True
        DISABLE_PAGINATION = 'terminal length 0'
        GET_CONFIG      ="show run"

OperatingSystems = {
        'IOS': CiscoIOS,
        'WebNS': CiscoWebNS,
        'OSX': AppleOSX,
        'SOS': SecureComputingSidewinder,
        'AOS': ArubaOS,
        'OBSD': OpenBSD,
        }

In my django app I have a model like so:

os_list = ((k,k) for k in Systems.OperatingSystems.iterkeys())

class Node(models.Model):
        name = models.CharField(max_length=100)
        ip   = models.IPAddressField(null=True, blank=True)
        description = models.TextField(null=True, blank=True)
        os   = models.CharField(choices=os_list,max_length=6, null=True, blank=True)
        transport = models.CharField(choices=transports, max_length=10)
        credentials = models.ForeignKey(Credential, blank=True, null=True)
        escalation_credentials = models.ForeignKey(Credential, blank=True, null=True, help_text="root or enable passwords if needed", related_name="enable_password" )

        def get_ip(self):
           return self.ip
        def __unicode__(self):
           return self.name + " - " + str(self.ip)

Meaningful snippet:

from ncm.management.commands import Systems
os_list = ((k,k) for k in Systems.OperatingSystems.iterkeys())

This iterates over my "OperatingSystems" dictionary's keys and constructs a tuple of (key,key) so that I can use it as a flat_choice for my os field.

Tagged as dictionary , django flat_choices , tuple
Written by Andrew Konkol on July 26th, 2012 | 0 Comments

Converting strings escaped string literals or raw string

I recenly wrote a django app which needed to store regex strings in a model.  Since I couldn't find a way to store raw strings in models I wrote a function to convert unicode or string into string literals.

def to_raw_string(s):
        if isinstance(s,str):
           s = s.encode('string-escape')
        if isinstance(s,unicode):
           s = s.encode('unicode-escape')
        return s

Tagged as django , python raw string , rawstring string , unicode
Written by Andrew Konkol on July 24th, 2012 | 0 Comments

Cisco Configuration Syntax Highlighting

I wrote a network config management tool and wanted to create my own syntax highlighting for cisco configs. It's pretty easy to create your own highlighter styles using Alex Gorbatchev's SyntaxHighlighter.

You can download my cisco brush here

shBrushCisco.js

SyntaxHighlighter.brushes.Cisco = function()
{
        var interface = 'interface FastEthernet';
        var keywords =  'ip snmp-server tacacs-server ntp line logging'+
                        'boot hostname banner end clock udld power ';
        var security =  'crypto';

        this.regexList = [
                { regex: new RegExp('description.*$', 'gm'),                    css: 'comments' },
                { regex: new RegExp('!.*$', 'gm'),                      css: 'comments' },
                { regex: new RegExp('^( no|no).*$', 'gm'),                      css: 'comments' },
                { regex: new RegExp('^version.*$', 'gm'),                       css: 'color2' },
                { regex: new RegExp('^service.*$', 'gm'),                       css: 'color2' },
                { regex: new RegExp('^aaa.*$', 'gm'),                   css: 'color3' },
                { regex: new RegExp('^interface.*$', 'gm'),                     css: 'color2' },
                { regex: new RegExp('^access-list.*$', 'gm'),                   css: 'color3' },
                { regex: new RegExp('^username.*$', 'gm'),                      css: 'color2' },
                { regex: new RegExp('^enable.*$', 'gm'),                        css: 'color2' },
                { regex: SyntaxHighlighter.regexLib.multiLineCComments,         css: 'comments' },                      // multiline comments
                { regex: SyntaxHighlighter.regexLib.doubleQuotedString,         css: 'string' },                        // strings
                { regex: SyntaxHighlighter.regexLib.singleQuotedString,         css: 'string' },                        // strings
                { regex: /^\s*#.*/gm,                                                                           css: 'preprocessor' },
                { regex: new RegExp(this.getKeywords(keywords), 'gm'),          css: 'color1' },                        // c# keyword
                { regex: new RegExp(this.getKeywords(interface),'gm'),          css: 'color2' },                        // c# keyword
                { regex: new RegExp(this.getKeywords(security), 'gm'),          css: 'color3' }                 // c# keyword
                ];

        this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
};

SyntaxHighlighter.brushes.Cisco.prototype       = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Cisco.aliases = ['cisco','network'];

some html file:

<head>
   <link rel="stylesheet" type="text/css" href="path_to/shCore.css" />
   <link rel="stylesheet" type="text/css" href="path_to/shThemeDefault.css"/>


   <script type="text/javascript" src="/static/syntax-highlighter/shCore.js"></script>
   <script type="text/javascript" src="/static/syntax-highlighter/shBrushCisco.js"></script>
   <script type="text/javascript">
      SyntaxHighlighter.all()
   </script>
</head>

<body>
<pre class="brush: cisco">
  interface GigabitEthernet0/0
   description to corp_lan
   ip address 192.168.1.10 255.255.0.0
   ip access-group FW_ACL_GigabitEthernet0/0 in
   no ip redirects
   no ip proxy-arp
   ip flow ingress
   ip nat inside
   ip virtual-reassembly in
   duplex full
   speed 100
   service-policy input GI0/0-COS-IN
</pre>
</body>

Tagged as cisco , highlighting syntax , syntaxhighlighter
Written by Andrew Konkol on July 24th, 2012 | 0 Comments