Advertisement
Guest User

NetKit network generator

a guest
Sep 22nd, 2010
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.92 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. ##############################################################################
  5. #  Copyright (C) 2010 Kenkeiras <[email protected]>
  6. #
  7. #  This program is free software. It comes without any warranty, to
  8. #  the extent permitted by applicable law. You can redistribute it
  9. #  and/or modify it under the terms of the Do What The Fuck You Want
  10. #  To Public License, Version 2, as published by Sam Hocevar.
  11. #
  12. #  See http://sam.zoy.org/wtfpl/COPYING for more details.
  13. ##############################################################################
  14.  
  15. import sys, string, os
  16. from random import *
  17. seed()
  18.  
  19. # Valores por defecto
  20. machines = 10 # Número de máquinas
  21. mem = 20      # Memoria por máquina
  22. switches = 2  # Número de switches
  23. mem_prop = 12 # Cantidad mínima de memoria por máquina
  24. tap = ( int(os.getuid()) == 0 ) # Si es root (y tiene permisos para crear nuevas interfaces)
  25.  
  26. # Clase de interfaz
  27. class interface:
  28.     def __init__(self, name, ip, colName, default = False):
  29.         self.name = name
  30.         self.ip = ip
  31.         self.default = default
  32.         self.col = colName
  33.  
  34. # Clase de host
  35. class host:
  36.     def __init__(self, name):
  37.         self.ifc = []
  38.         self.name = name
  39.  
  40.     # Se conecta con una IP a un dominio de colisión
  41.     def connect(self, ip, col, default = False):
  42.         iface = interface("eth"+str(len(self.ifc)), ip, col, default)
  43.         self.ifc.append(iface)
  44.        
  45.  
  46. # Dominio de colision
  47. class colDom:
  48.     def __init__(self, name, ipNum):
  49.         self.host = host("SW" + name) # Se añade el prefijo para distinguir
  50.         self.name = name              # Switches
  51.         self.list = []
  52.         self.cip = 1
  53.         self.ipRange = "10.0." + str(ipNum)
  54.  
  55.     # Se obtiene una IP no usada (y se considera usada)
  56.     def getIdle(self):
  57.         if (self.cip < 255):
  58.             self.cip += 1
  59.             return self.ipRange + "." + str(self.cip)
  60.  
  61.         else:
  62.             return None
  63.  
  64. def buildFileTree(rootFolder):
  65.     os.mkdir(str(rootFolder))
  66.  
  67. def genLab(net, col, mem, tap = False):
  68.  
  69.     # Se genera el archivo lab.conf
  70.     f = open("lab.conf", "w")
  71.     f.write("""LAB_DESCRIPTION=""
  72. LAB_VERSION=""
  73. LAB_AUTHOR=""
  74. LAB_EMAIL=""
  75. LAB_WEB=""
  76. """)
  77.  
  78.     # Crea el núcleo de la red
  79.     buildFileTree("BBOSS")
  80.     bf = open("BBOSS.startup", "w")
  81.     f.write("BBOSS[mem]=" + str(mem) + "\n")
  82.     f.write("BBOSS[eth0]=" + "BigBoss" + "\n")               # Conexión al núcleo de la red
  83.     if (tap):
  84.         f.write("BBOSS[eth1]=tap,192.168.254.1,192.168.254.2\n") # Conexión a la red exterior
  85.  
  86.     bf.write("ifconfig eth0 10.0.0.1 netmask 255.255.255.0\n")
  87.     # Se incluyen las máquinas y el gasto en memoria
  88.     for i in net:
  89.         f.write(str(i.name) + "[mem]=" + str(mem) + "\n")
  90.  
  91.     # Y los switches
  92.     for i in col:
  93.         f.write(str(i.host.name) + "[mem]=" + str(mem) + "\n")
  94.  
  95.     # Se incluyen las interfaces y dominios de colision
  96.     for i in net:
  97.         for iface in i.ifc:
  98.             f.write(str(i.name) + "[" + str(iface.name) + "]=" +\
  99.                      str(iface.col) + "\n")
  100.  
  101.     for i in col:
  102.         for iface in i.host.ifc:
  103.             f.write(str(i.host.name) + "[" + str(iface.name) + "]=" +\
  104.                      str(iface.col) + "\n")
  105.  
  106.  
  107.     f.close()
  108.  
  109.     for i in net:
  110.         # Se crean los archivos .startup
  111.         f = open(str(i.name) + ".startup", "w")
  112.         #f.write("sh /etc/rc.d/rc.stup\n")
  113.         f.close()
  114.  
  115.         # Y el árbol de archivos
  116.         buildFileTree(str(i.name))
  117.  
  118.         f = open(str(i.name) + ".startup", "a")
  119.         for iface in i.ifc: # Se configuran las interfaces
  120.             f.write("ifconfig " + iface.name + " " + iface.ip + " netmask 255.255.255.0\n")
  121.             f.write("ifconfig " + iface.name + " up\n")
  122.             tgt = iface.ip.split(".")
  123.             if (iface.default): # Y el enrutado
  124.                 f.write("route add default gw " + string.join(tgt[ : 3 ], \
  125.                         ".") + ".1\n")
  126.  
  127.         f.close()
  128.  
  129.    
  130.     for c in col:
  131.         i = c.host
  132.         # Se crean los archivos .startup
  133.         f = open(str(i.name) + ".startup", "w")
  134.         #f.write("/etc/rc.d/rc.stup start\n")
  135.         f.close()
  136.  
  137.         # Y el árbol de archivos
  138.         buildFileTree(str(i.name))
  139.  
  140.         f = open(str(i.name) + ".startup", "a")
  141.         tgt = ""
  142.         src = ""
  143.         def_if = ""
  144.         for iface in i.ifc: # Se configuran las interfaces
  145.             if not("10.0.0." in iface.ip):
  146.                 src = iface.ip.split(".")
  147.             else:
  148.                 def_if = iface.name
  149.                 tgt = iface.ip
  150.  
  151.             f.write("ifconfig " + iface.name + " " + iface.ip + " netmask 255.255.255.0\n")
  152.  
  153.         if (tgt != "") and (src != ""):
  154.             bf.write("route add -net " + string.join(src[ : 3 ], ".") + ".0 gw " + tgt + " netmask 255.255.255.0 \n")
  155.         else:
  156.             print >>sys.stderr, "Switch", i.name, "sin conexion a BBOSS (¿?)"
  157.  
  158.         f.write("route add default gw 10.0.0.1 dev " + def_if + "\n") # Y el enrutado
  159.         f.write("echo 1 >> /proc/sys/net/ipv4/ip_forward\n") # Se permite forwardear paquetes
  160.  
  161.         f.close()
  162.  
  163.     bf.write("echo 1 >> /proc/sys/net/ipv4/ip_forward\n")
  164.     bf.close()        
  165.  
  166. # Se genera la red a partir de el número de máquinas
  167. # su gasto en memoria y el numero de dominios de colision
  168. def Netbuild(nmachine, mem, sn, tap = False):
  169.  
  170.     colName = "CD"       # Prefijo de los dominios de colision
  171.     machName = "MACH"    # Prefijo de las máquinas
  172.     prop = (nmachine/sn) # Proporción máquinas/switches
  173.  
  174.     print 'Memoria por máquina:',mem,'MB'
  175.     print prop,'máquinas por switch'
  176.     print 'Generando (',nmachine + 1,') máquinas...'
  177.  
  178.     net = []
  179.     col = []
  180.     ipNet = []
  181.     for i in range(0, nmachine): # Se generan las máquinas
  182.         h = host(machName + str(i))
  183.         net.append(h)
  184.  
  185.     j = 0
  186.     print 'Generando (',sn,') switches...'
  187.     for i in range(1, sn + 1):
  188.         col.append(colDom(colName + str(i), i)) # Se genera el dominio de colision
  189.  
  190.         col[-1].host.connect( col[-1].ipRange + ".1", col[-1].name, True) # Se conecta el switch al dominio de colision
  191.         col[-1].host.connect( "10.0.0." + str(i + 1), "BigBoss", True)    # Y al núcleo de la red
  192.         while (j < prop * (i)): # Se le asignan las máquinas correspondientes
  193.  
  194.             ip = col[-1].getIdle() # Se obtiene una IP válida
  195.             if (ip == None):
  196.                 print >>sys.stderr, "Exceso de máquinas por dominio de colision"
  197.                 exit(1)
  198.  
  199.             net[j].connect(ip, col[-1].name, True) # Se le asigna a la máquina como salida por defecto
  200.  
  201.             j += 1
  202.  
  203.     # Se asignan las máquinas que sobran
  204.     while (j < len(net)):
  205.         n = randint(0, len(col) - 1)
  206.         ip = col[-1].getIdle() # Se obtiene una IP válida
  207.         if (ip == None):
  208.             print >>sys.stderr, "Exceso de máquinas por dominio de colision"
  209.             exit(1)
  210.  
  211.         net[j].connect(ip, col[-1].name, True) # Se le asigna a la máquina como salida por defecto
  212.         j += 1
  213.        
  214.  
  215.     genLab(net, col, mem, tap) # Se generan los archivos de laboratorio
  216.  
  217.  
  218. if __name__=="__main__":
  219.  
  220.     if (len(sys.argv) > 1):
  221.         if (sys.argv[1] in "clean") and ("clean".index(sys.argv[1]) == 0):
  222.             os.system("rm -Rf MACH* SWCD* BBOSS* lab.conf")
  223.             sys.exit(0)
  224.  
  225.         else:
  226.             max_mem = int(raw_input('Máximo de memoria que utilizara(MB): '))
  227.             switches = int(raw_input('Número de switches que se utilizarán: '))
  228.             machines = int(raw_input('Número total de máquinas que se utilizarán: '))
  229.             mem = int(max_mem / (switches + machines) )
  230.  
  231.     if (machines < 1):
  232.         print 'Datos invalidos'
  233.         sys.exit(1)
  234.  
  235.     elif ( mem < mem_prop):
  236.         print 'No hay suficiente memoria para cada máquina'
  237.         sys.exit(1)
  238.  
  239.     Netbuild(machines - 1, mem, switches, tap)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement