Exemplo n.º 1
0
 def createCase5(self):
     self.element1=Host(300,200,0,0)
     self.element2=Host(1000,200,0,0)
     self.element3=Router(650,200,0,0)
     self.element4=Host(650,400,0,0)
     self.Bus1=Bus(300,205,1000,205)
     self.Bus2=Bus(660,200,660,400)
Exemplo n.º 2
0
 def scan(self, timeout, retry):
     for ip in Utils.get_all_ips():
         if not self.main.HostMgr.has_host(ip):
             mac = get_mac(ip, timeout, retry)
             if mac is not None:
                 host = Host(self.main, ip, mac)
                 host.start()
                 self.main.HostMgr.append_host(host)
Exemplo n.º 3
0
def initHost(ip):
    #print('Scanning', ip)
    host = Host(ip)
    host.getInterfaces()
    if host.online == False:
        #print('Host with ip', ip, 'offline!')
        print(ip)
    host.hasBridge()
    return host
Exemplo n.º 4
0
    def __init__(self,
                 name,
                 logfile_object=sys.stdout,
                 u_name=U_NAME,
                 passwd=PASSWD):

        Host.__init__(self, name)
        self.name = name
        self.logfile = logfile_object
        self.user = u_name
        self.passwd = passwd
Exemplo n.º 5
0
    def __init__(self,name,u_name = U_NAME,passwd = PASSWD,logon = 1):
	
	Host.__init__(self,name)

        self.name           = name
        self.user           = u_name
        self.passwd         = passwd
        self.ssh            = ""
        
	if logon == 1:
	    
            self.logon()
Exemplo n.º 6
0
def getHostList(queue='all.q'):
    """ Return the host that are in the chosen 'queue' """
    from Host import Host

    queue_hosts_bin = Popen(['qconf', '-sq', queue], stdout=PIPE)
    out, err = queue_hosts_bin.communicate()

    hostlist = []

    if not err:

        queue_hostlist = ''

        host_list_str = [
        ]  # a simple string list of the hosts before they are objects

        for o in out.split('\n'):
            if 'hostlist' in o:
                queue_hostlist = o.split()[1:]

        for hg in queue_hostlist:
            if hg.startswith('@'):  # hostgroup

                hg_hosts_bin = Popen(['qconf', '-shgrp', hg], stdout=PIPE)

                out, err = hg_hosts_bin.communicate()

                if not err:
                    hg_hosts_str_list = out.split()

                    for l in hg_hosts_str_list:
                        if 'blue-bolt.local' in l and l not in host_list_str:
                            host_list_str.append(l)
                            hostlist.append(Host(l))
                else:
                    error(err)
                    break

            elif hg.startswith(queue):  # individual host

                this_host = hg.strip('%s@' % queue)

                if this_host not in host_list_str:

                    hostlist.append(Host(this_host))

        return hostlist

    else:
        error(err)
        return None
Exemplo n.º 7
0
 def GetHosts(self):
     if not hasattr(self, "hosts"):
         self.hosts = []
         for hca, ips in TOPO.iteritems():
             for ip in ips[:-1]:
                 self.hosts.append(Host(ip, self.Logger))
     return self.hosts
Exemplo n.º 8
0
    def __init__(self, uri='mongodb://mongo:27017', max_conn=1):

        # if max_connid null or is not 1-200 exception
        if not max_conn or not isinstance(max_conn, int) or max_conn > 200 or max_conn < 1:
            raise MongoPoolInitException(errorMsg='max_conn not is {}'.format(max_conn))
        Resource.__init__(self)
        self.__max_conn = max_conn
        self.__uri = uri
        self.idle = max_conn
        self.busy = 0
        
        config = Config(DB_CFG).config
        dbname = 'vmmgr'
        dbinfo = {
            "name": config.get(dbname, 'name'),
            "user": config.get(dbname, 'user'),
            "pwd": config.get(dbname, 'pwd')
        }
        self.name = dbinfo['name']
        self.user = dbinfo['user']
        self.pwd  = dbinfo['pwd']

        self.pool = ConnectPool(self.idle,self.busy)
        self.__prepare_conn()

        self.version = config.get('global', 'version')

        self.putChild("", self)
        self.putChild("virtualmachine", VirtualMachine(self.pool))
        self.putChild("host", Host(self.pool))
        self.putChild("adaccount", AdAccount(self.pool))
Exemplo n.º 9
0
    def analyse_pingscan(self, host, infos, output):
        if infos['nmap']['scanstats']['totalhosts'] != "1":
            print("Probleme avec le nombre d'hosts")
        elif infos['nmap']['scanstats']['totalhosts'] == "1":
            if infos['nmap']['scanstats']['uphosts'] == "1":
                if self.monitored_hosts.has_key(host):
                    self.monitored_hosts[host].setLastPing(time())

                    if not self.monitored_hosts[host].isUp():
                        self.monitored_hosts[host].up = True
                        self.log(host, "is up")

                    self.compareMacAddr(host, output)
                    self.compareName(host, output)

                    self.monitored_hosts[host].setPinging(False)
                else:
                    self.monitored_hosts[host] = Host(host,
                                                      infos['scan'][host],
                                                      time(), self.verbose)
                    self.log(host, "Detected !")
                    self.compareMacAddr(host, output)
            else:  # is down
                if self.monitored_hosts.has_key(host):
                    self.monitored_hosts[host].setPinging(False)
                    self.monitored_hosts[host].up = False
                    self.log(host, "is down")
Exemplo n.º 10
0
 def newByXMLFile(path):
     tree = ET.parse(path)
     root = tree.getroot()
     host = []
     for each in root.findall('host'):
         host.append(Host.fromNode(each))
     return Target(tree, root, host)
Exemplo n.º 11
0
    def __init__(self,
                 ARRIVE_RATE=None,
                 CHANNEL_RATE=None,
                 TOTAL_PACKET=None,
                 NUMBER_OF_HOST=None):
        config = configparser.ConfigParser()
        config.read("configuration_file.ini")
        self.ARRIVE_RATE = float(config["DEFAULT"]["ARRIVE_RATE"])
        self.NUMBER_OF_HOST = int(config["DEFAULT"]["NUMBER_OF_HOST"])
        self.TOTAL_PACKET = int(config["DEFAULT"]["TOTAL_PACKET"])
        self.CHANNEL_RATE = int(config["DEFAULT"]["CHANNEL_RATE"])

        self.channel = Channel(self.CHANNEL_RATE, self)
        self.host_array = [Host(n, self) for n in range(self.NUMBER_OF_HOST)]
        self._previousEvent = None

        # variables and counters
        self.timeLineEvent = []
        self.counter_array = []
        self.packet_array = []
        self.event_list = deque()
        self.busy_time = 0
        self.current_time = 0
        self.packet_counter = 0
        self.event_counter = 0

        self.number_in_system = []
Exemplo n.º 12
0
    def setUp(self):
        global host, vm

        if host is None:
            #print('Connecting to %s...' % hostName)
            host = Host(hostName, os.getenv('VIM_E2E_USER'),
                        os.getenv('VIM_E2E_PASSWORD'))
            host.Connect()
            #print('Creating vm %s...' % vm)
            CreateVm(vm)

            def onExit():
                global host, vm

                #print('Deleting vm %s...' % vm)
                DeleteVm(host, vm)
                host.Logout()

            atexit.register(onExit)
Exemplo n.º 13
0
 def add_host(self, hostname, value):
     # Have to strip "." because MongoDB doesn't like them for key names
     clean_hostname = hostname.replace(".", "___")
     if self.hosts.has_key(clean_hostname):
         self.logger.err(clobber_host_blue_str % (self.teamname, hostname))
     else:
         self.logger.err(add_host_blue_str % (self.teamname, hostname))
     this_queue = Queue.Queue()
     self.hosts[clean_hostname] = Host(self.teamname, hostname, value, self.logger, self.dns_servers, this_queue)
     self.hosts_rounds[clean_hostname] = False
     self.host_queues[clean_hostname] = this_queue
Exemplo n.º 14
0
	def getHosts(self):
		# We're going to iterate over all the arps, and turn them into hosts.
		print('Populating hosts from list of', len(self.globalArpTable), 'ARP resolutions.')
		for arp in self.globalArpTable:
			ip = arp['ip']
			mac = arp['mac']
			source = self.routers[arp['source']]
			interface = Interface(mac)
			interface.ip = ip
			try:
				# Assuming that this host exists.
				host = self.hosts[ip]
			except KeyError:
				# If it doesn't, then add it in.
				host = Host(ip)
				self.hosts[ip] = host
			# Then, new or not, add the interface information.
			host.interfaces[mac] = interface
			host.arpNeighbors[ip] = source
		print('Showing', len(self.hosts), 'hosts!')
		return self.hosts
Exemplo n.º 15
0
    def checkZabbixAgainstArp(self):
        # When Zabbix and ARP think that an address is registered to a
        # different MAC address, that can be cause for alarm.

        #FIXME Use the ORM
        q = 'select zabhosts.mac as zabmac, zabhosts.ip, arp.mac as arpmac from ' +\
                'zabhosts, arp where zabhosts.mac is not null and zabhosts.ip is not '+\
                'null and zabhosts.ip = arp.ip and zabhosts.mac != arp.mac;'
        mismatches = self.execute(q)
        offline = []
        unknown = []
        differentLink = []
        if mismatches:
            for mismatch in mismatches:
                #print(mismatch.ip)
                # Make a host, get the data from the host.
                host = Host(mismatch.ip)
                host.getInterfaces()
                if host.online:
                    # See if the address is among its interfaces.
                    if host.hasMac(mismatch.zabmac):
                        differentLink.append(mismatch) 
                    else:
                        print(mismatch.ip, 'mismatched for unknown reasons.')
                        unknown.append(mismatch)
                        #print(len(unknown))
                else:
                    offline.append(mismatch)
        else:
            print('There are no mismatched addresses.')

        print('There are', len(offline), 'offline hosts.')
        print('There are', len(differentLink), 'hosts that were simply',
            'detected on a different link.')
        print('There are', len(unknown), 'undiagnosed hosts.')
        print('Undiagnosed hosts: %s' % unknown)
    def host_makes_move(self, host_move):
        self.host_move = host_move

        if host_move == "0":
            Host.send_rock()
        elif host_move == "1":
            Host.send_paper()
        elif host_move == "2":
            Host.send_scissors()

        self.set_move_labels()
Exemplo n.º 17
0
 def __getHostfromConfig(self, maxProcess, maxError):
     lst = config["hosts"]
     pcList = []
     for host in lst:
         h = Host(host["name"], host["user"], crypto.decrypt(host["pass"]))
         h.setMaxProcess(maxProcess)
         h.setMaxErrors(maxError)
         self.log.debug("Host %s extracted from config file." % h.getHostName())
         pcList.append(h)
     self.log.debug("Total number of hosts is: %i" % len(pcList))
     return pcList
Exemplo n.º 18
0
    def config_generic_host(self, cfg):
        """
        :type cfg: HostDef
        :return: Host
        """

        # interface is a list of maps: {iface, bridge, ips, mac}
        h = Host(cfg.name, NetNSCLI(cfg.name), CREATENSCMD, REMOVENSCMD, self)
        self.hosts[cfg.name] = h
        self.interfaces_for_host[cfg.name] = {}
        for iface in cfg.interface_list:
            bridge = self.get_bridge_from_link_config(iface.bridge_link)
            self.add_virt_interface(h, iface.name, bridge, iface.ip_list,
                                    iface.mac_address)

        self.generic_hosts.append(h)
        return h
Exemplo n.º 19
0
def main():
    target_spec = parse_args()

    # Stealth scan, OS scan, and MAC resolution require superuser priveleges
    elevate(graphical=False, show_console=False)

    # Enable p0f passive scan while nmap is scanning
    with P0f_client("p0f.socket") as p0f_client:
        nm = PortScanner()

        # If no target spec specified, detect subnet automatically
        if target_spec is None:
            target_spec = get_network_parameters()
            print("Using automatic target_spec: ", target_spec)

        # Invoke nmap scanner
        print("Starting scan")

        try:
            nm.scan(target_spec,
                    arguments="-sS -sU -p 22 -sV -O -T4 --script=banner")
        except KeyboardInterrupt as e:
            print("nmap scan interrupted.")

        # Process hosts
        hosts = dict()

        for host in nm.all_hosts():
            try:
                hosts[host] = Host(host, nm, p0f_client)
            except Exception as e:
                print("Error parsing host ", host, " ", e)
                raise e  # TODO - REMOVE

        print(len(hosts), " hosts scanned with target spec: ", target_spec)

        # Create XML output
        xml = XML(hosts)

        with open("host_report.xml", "w") as out_file:
            out_file.write(xml.get_xml())
Exemplo n.º 20
0
    def __init__(self,
                 ARRIVE_RATE=0.1,
                 SERVICE_RATE=11e6,
                 TOTAL_PACKET=1000,
                 NUMBER_OF_HOST=10):
        self.channel = Channel(SERVICE_RATE, self)
        self.host_array = [Host(n, self) for n in range(NUMBER_OF_HOST)]
        self._previousEvent = None

        # constants
        self.ARRIVE_RATE = ARRIVE_RATE
        self.SERVICE_RATE = SERVICE_RATE
        self.TOTAL_PACKET = TOTAL_PACKET

        # variables and counters
        self.timeLineEvent = []
        self.event_list = deque()
        self.busy_time = 0
        self.current_time = 0
        self.packet_counter = 0
        self.event_counter = 0

        self.number_in_system = []
Exemplo n.º 21
0
    def __init__(self, host,username= "", password= "",stdprompt=tek_prompt_regex):
        """tek specific init method.  Basically just filling in the blanks."""

        Host.__init__(self, host, username, password, stdprompt)
        log.output("G-35 object for host %s created." % host)
Exemplo n.º 22
0
 def __init__ (self, screen, x, y):
     Host.__init__(self, screen, x, y)
     self.selectable = True        
     self.corespondent = self.name
     self.timer = 0
     self.color = (64, 128, 223)
Exemplo n.º 23
0
 def createCase2(self):
     self.element1=Host(300,200,0,0)
     self.element2=Router(900,200,0,0)
     self.Bus1=Bus(300,205,900,205)
Exemplo n.º 24
0
class StartMaker():

    ip = IP()
    host = []
    enlacePP = []
    enlacePP = []
    switch = []
    router = []
    nic_host = []
    nic_switch = []
    nic_router = []
    
    # All Class Objects store in arrays[n] started 0 to n-1 
    
    # Start Hosts 0~11
    for n in range(0,12):
        host.append(Host())
    
    # Start Enlace 0~21
    for n in range(0,22):
        enlacePP.append(EnlacePP())
    
    # Start Switchs 0~2
    for n in range(0,3):
        switch.append(Switch())

    switch[0].setNome('switch_0')
    switch[1].setNome('Switch_1')
    switch[2].setNome('Switch_2')
    
    # Start Routers 0~2
    for n in range(0,3):
        router.append(Router())

    router[0].setNome('Router_0')
    router[1].setNome('Router_1')
    router[2].setNome('Router_2')

    # Start Hosts-NICs ( 12th )
    # NIC receved MAC, Enlace and Host
    # Network 201.10.0.0
    nic_host.append(NIC('01:0A:00:FF:0A:01',enlacePP[0],host[0]))
    nic_host.append(NIC('02:0A:00:FF:0A:02',enlacePP[1],host[1]))
    nic_host.append(NIC('03:0A:00:FF:0A:03',enlacePP[2],host[2]))
    nic_host.append(NIC('04:0A:00:FF:0A:04',enlacePP[3],host[3]))
    # Network 200.171.0.0
    nic_host.append(NIC('05:0B:00:EE:0B:05',enlacePP[5],host[4]))
    nic_host.append(NIC('06:0B:00:EE:0B:06',enlacePP[6],host[5]))
    nic_host.append(NIC('07:0B:00:EE:0B:07',enlacePP[7],host[6]))
    nic_host.append(NIC('08:0B:00:EE:0B:08',enlacePP[8],host[7]))
    # Network 192.168.0.0
    nic_host.append(NIC('09:0C:00:CC:0C:09',enlacePP[10],host[8]))
    nic_host.append(NIC('0A:0C:00:CC:0C:0A',enlacePP[11],host[9]))
    nic_host.append(NIC('0B:0C:00:CC:0C:0B',enlacePP[12],host[10]))
    nic_host.append(NIC('0C:0C:00:CC:0C:0C',enlacePP[13],host[11]))

    # Start Switchs-NICs ( 15th )
    # Nic receved MAC, Enlace and Switch
    # Switch 0
    nic_switch.append(NIC('040A7119SW01',enlacePP[0],switch[0]))
    nic_switch.append(NIC('040A7119SW02',enlacePP[1],switch[0]))
    nic_switch.append(NIC('040A7119SW03',enlacePP[2],switch[0]))
    nic_switch.append(NIC('040A7119SW04',enlacePP[3],switch[0]))
    # Dedicated Router 0 - Network 201.10.0.0
    nic_switch.append(NIC('040A7119SW05',enlacePP[4],switch[0]))# Local Network 201.10.0.0

    # Switch 1
    nic_switch.append(NIC('040A7119SW06',enlacePP[5],switch[1]))
    nic_switch.append(NIC('040A7119SW07',enlacePP[6],switch[1]))
    nic_switch.append(NIC('040A7119SW08',enlacePP[7],switch[1]))
    nic_switch.append(NIC('040A7119SW09',enlacePP[8],switch[1]))
    # Dedicated Router 1 - Network 200.171.0.0
    nic_switch.append(NIC('0040A7119SW10',enlacePP[9],switch[1]))# Local Network 200.171.0.0

    # Switch 2
    nic_switch.append(NIC('040A7119SW11',enlacePP[10],switch[2]))
    nic_switch.append(NIC('040A7119SW12',enlacePP[11],switch[2]))
    nic_switch.append(NIC('040A7119SW13',enlacePP[12],switch[2]))
    nic_switch.append(NIC('040A7119SW14',enlacePP[13],switch[2]))
    # Dedicated Router 2 - 192.168.0.0
    nic_switch.append(NIC('040A7119SW15',enlacePP[14],switch[2]))# Local Network 192.168.0.0

    # Start Routers-NICs ( 12th )
    # Router 0 Networks 10.0.0.0 and 201.10.0.0 
    nic_router.append(NIC('040A7119SR01',enlacePP[4],router[0])) # Network 201.10.0.0 - Local
    nic_router.append(NIC('040A7119SR02',enlacePP[15],router[0])) # Network 10.0.0.0
    nic_router.append(NIC('040A7119SR03',enlacePP[16],router[0])) # unused
    nic_router.append(NIC('040A7119SR04',enlacePP[17],router[0])) # unused

    # Router 1 Networks 10.0.0.0, 11.0.0.0 and 200.171.0.0
    nic_router.append(NIC('040A7119SR05',enlacePP[15],router[1])) # Network 10.0.0.0 - 201.10.0.0
    nic_router.append(NIC('040A7119SR06',enlacePP[18],router[1])) # Network 11.0.0.0 - 192.168.0.0
    nic_router.append(NIC('040A7119SR07',enlacePP[9],router[1])) # Network 200.171.0.0 - Local
    nic_router.append(NIC('040A7119SR08',enlacePP[19],router[1]))  # Internet

    # Router 2 Networks 11.0.0.0 and 192.168.0.0
    nic_router.append(NIC('040A7119SR09',enlacePP[18],router[2])) # Network 11.0.0.0
    nic_router.append(NIC('040A7119SR10',enlacePP[14],router[2])) # Network 192.168.0.0 - Local
    nic_router.append(NIC('040A7119SR11',enlacePP[20],router[2])) # unused
    nic_router.append(NIC('040A7119SR12',enlacePP[21],router[2])) # unused    
    
    # Set Routers IP
    router[0].setIP('201.10.0.1')
    router[1].setIP('200.171.0.1')
    router[2].setIP('192.168.0.1')
    
    # Adding Routes
    #router.setRota(Rota('<destination>','<route>','<mask>', '<metric>', '<MAC>'))
    # Router 0 to Router 1 Network A
    router[0].setRota(Rota('201.10.0.0','201.10.0.1','255.255.0.0', '0', '040A7119SR01')) # Network 201.10.0.0 - Local
    router[0].setRota(Rota('200.171.0.0','200.171.0.1','255.255.0.0', '0', '040A7119SR02'))
    router[0].setRota(Rota('192.168.0.0','192.168.0.1','255.255.0.0', '0', '040A7119SR02'))
    router[0].setRota(Rota('10.0.0.0','10.0.0.1','255.0.0.0', '0', '040A7119SR02'))
    router[0].setRotaDefault(Rota('10.0.0.0','10.0.0.1','255.0.0.0', '0', '040A7119SR02'))

    # Router 1 Network 01, 02 and 04
    router[1].setRota(Rota('200.171.0.0','200.171.0.1','255.255.0.0', '0', '040A7119SR07')) # Network 200.171.0.0 - Local
    router[1].setRota(Rota('201.10.0.0','201.10.0.1','255.255.0.0', '0', '040A7119SR05')) # Network 10.0.0.0 - 201.10.0.0
    router[1].setRota(Rota('10.0.0.0','10.0.0.1','255.0.0.0', '0', '040A7119SR05')) # Network 10.0.0.0 - R05
    router[1].setRota(Rota('192.168.0.0','192.168.0.1','255.255.0.0', '0', '040A7119SR06')) # Network 11.0.0.0 - 192.168.0.0
    router[1].setRota(Rota('11.0.0.0','11.0.0.1','255.0.0.0', '0', '040A7119SR06')) # Network 11.0.0.0 - R06
    router[1].setRotaDefault(Rota('0.0.0.0','0.0.0.0','0.0.0.0', '0', 'INTERNET'))

    # Router 2 Network 02 and 05
    router[2].setRota(Rota('192.168.0.0','192.168.0.1','255.255.0.0', '0', '040A7119SR10')) # Network 192.168.0.0 - Local
    router[2].setRota(Rota('11.0.0.0','11.0.0.1','255.0.0.0', '0', '040A7119SR09'))
    router[2].setRota(Rota('200.171.0.0','200.171.0.1','255.255.0.0', '0', '040A7119SR09'))
    router[2].setRota(Rota('201.10.0.0','201.10.0.1','255.255.0.0', '0', '040A7119SR09'))
    router[2].setRotaDefault(Rota('11.0.0.0','11.0.0.1','255.0.0.0', '0', '040A7119SR09'))

# HOSTs reset IPs#
    for n in range(0,12):
        host[n].setIP('ip-not-found')
        host[n].setMascara('255.255.0.0')
        host[n].setLigado(False)
        nic_host[n].setLigado(False)
        nic_host[n].setTDados(False)
        host[n].resetPing()

    # SWITCHs reset#        
    switch[0].setLigado(False)
    for n in range(0,5):
        nic_switch[n].setLigado(False)
        nic_switch[n].setTDados(False)

    switch[1].setLigado(False)
    for n in range(5,10):
        nic_switch[n].setLigado(False)
        nic_switch[n].setTDados(False)
    
    switch[2].setLigado(False)
    for n in range(10,15):
        nic_switch[n].setLigado(False)
        nic_switch[n].setTDados(False)

    # ROUTERs #
    router[0].setLigado(False)
    for n in range(0,4):
        nic_router[n].setLigado(False)
        nic_router[n].setTDados(False)

    router[1].setLigado(False)
    for n in range(4,8):
        nic_router[n].setLigado(False)
        nic_router[n].setTDados(False)
    
    router[2].setLigado(False)
    for n in range(8,12):
        nic_router[n].setLigado(False)
        nic_router[n].setTDados(False)
Exemplo n.º 25
0
#!/usr/bin/env python
# -*- coding:utf8 -*-

import os

from Sinet import Sinet
from Hub import Hub
from Switch import Switch, SwitchBroadcast
from Host import Host
from Message import Message
from Router import Router

sinet = Sinet()
client_1 = Host('192.168.2.10', '255.255.255.0', '112:211:11:11')
client_2 = Host('192.168.2.20', '255.255.255.0', '113:1133:11:11')
client_3 = Host('192.168.2.30', '255.255.255.0', '11:22:11:22:11')


def menu():
    os.system('clear')
    print '%s MENU %s' % ('-' * 30, '-' * 40)
    op = int(
        raw_input('''
	1 - Criar ambiente com Hub
	2 - Criar ambiente com Switch s/ broadcast
	3 - Criar ambiente com Switch c/ broadcast
	4 - Criar ambiente com Roteador
	:'''))

    escolha(op)
Exemplo n.º 26
0
 def createCase1(self):
     self.element1=Host(300,200,0,0)
     self.element2=Host(900,200,0,0)
     self.Bus1=Bus(300,205,900,205)
Exemplo n.º 27
0
    def generatgeView(self, rHosts, subnetSpace, targetPort, NCDSPort,
                      HoneyPort, numSubnets, minHP, maxHP, Strategy):

        self.targetsubnet = numSubnets
        self.lowerSubnet = numSubnets / 2
        self.upperSubnet = 0
        #generate specified number of subnets
        for s in range(1, numSubnets):
            self.getAvaiSubnet(numSubnets)

        hosts = []
        #assign hosts to subnets, and deceive their data
        for k in rHosts.keys():
            if k != NCDSPort and k != HoneyPort:
                #create new host object
                realip = rHosts[k].split("/")[0]
                realmac = rHosts[k].split("/")[1]
                if k == targetPort:
                    self.target = Host(self.getShortnameHost(), realip,
                                       realmac, k)
                    #get subnet address for target
                    self.target = self.setAvailableSubnetAddress(
                        subnetSpace, numSubnets, self.target, targetPort)
                    #print(str(self.target.deceptiveIP))
                else:
                    host = Host(self.getShortnameHost(), realip, realmac, k)
                    #get subnet address for host
                    host = self.setAvailableSubnetAddress(
                        subnetSpace, numSubnets, host, targetPort)
                    #print(str(host.deceptiveIP))

        #assign honeypots to subnets
        realHoneyIP = rHosts[HoneyPort].split("/")[0]
        realHoneyMac = rHosts[HoneyPort].split("/")[1]
        for subKey in self.subnetList.keys():
            numHoneypots = random.randint(minHP, maxHP)
            for hp in range(1, numHoneypots):
                subnet = self.subnetList[subKey]
                hpAddr = self.getAvaiHoneypotforSubnet(subnet)
                honeyAddr = str(subnetSpace[:-2]) + "." + str(
                    subnet.number) + "." + str(hpAddr)
                honeypot = Honeypot(self.getShortnameHoneypot(),
                                    realHoneyIP, realHoneyMac, honeyAddr,
                                    self.randMac(), HoneyPort)
                self.subnetList[subnet.number].honeypots.append(honeypot)
                #print("Honeypot " + honeyAddr)

        #create honeyrouters
        routerMac = self.randMac()
        targetSubnet = int(self.target.deceptiveIP.split(".")[2])

        subnet = self.subnetList[targetSubnet]
        subnetAddr = str(subnetSpace[:-2]) + "." + str(subnet.number) + ".1"
        hr = Honeyrouter(self.getShortnameHoneyrouter(), subnetAddr, routerMac,
                         NCDSPort)
        subnet.honeyrouter.append(hr)
        gateway = hr.shortName
        self.subnetList[subnet.number] = subnet
        self.honeyrouterList.append(hr)

        for subKey in self.subnetList.keys():
            subnet = self.subnetList[subKey]
            if subnet.number != targetSubnet:
                subnetAddr = str(subnetSpace[:-2]) + "." + str(
                    subnet.number) + ".1"
                hr = Honeyrouter(self.getShortnameHoneyrouter(), subnetAddr,
                                 routerMac, NCDSPort)
                subnet.honeyrouter.append(hr)
                self.subnetList[subKey] = subnet
                self.honeyrouterList.append(hr)

        #generate routes
        numhops = 1
        for subKey in self.subnetList.keys():
            subnet = self.subnetList[subKey]
            targetSubnet = int(self.target.deceptiveIP.split(".")[2])

            if subnet.number != targetSubnet:
                numhops += 1
                #numhops=random.randint(2,networkDiameter)
                hostIdx = 0
                for host in subnet.hosts:
                    r = Route(self.target, host)
                    hostSubnet = int(host.deceptiveIP.split(".")[2])
                    #hops = int(math.fabs(hostSubnet-targetSubnet))

                    #max sub dist min hop dist
                    if Strategy == "minhop_maxsub":
                        hops = numSubnets - hostSubnet

                    if Strategy == "maxhop_maxsub":
                        #max sub dist max hop dist
                        hops = hostSubnet

                    for hop in range(0, hops):
                        r.addHop(self.honeyrouterList[hop])
                    self.routeList.append(r)
                    host.distance = hops
                    #subnet.hosts.insert(hostIdx,host)
                    #hostIdx+=1
                for honeypot in subnet.honeypots:
                    r = Route(self.target, honeypot)
                    for hop in range(0, numhops - 1):
                        r.addHop(self.honeyrouterList[hop])
                    self.routeList.append(r)
            else:
                for host in subnet.hosts:
                    r = Route(self.target, host)
                    self.routeList.append(r)
                for honeypot in subnet.honeypots:
                    r = Route(self.target, honeypot)
                    self.routeList.append(r)

        #set gateway

        printer = NetworkPrinter()
        realhosts = printer.printView(self.target, self.subnetList,
                                      self.routeList, targetPort, gateway)
        #for printhost in realhosts:
        #print("realhosts.append(\"" + printhost + "\")")
        return (realhosts, self.targetsubnet)
Exemplo n.º 28
0
class TestHost(unittest.TestCase):
    
    def setUp(self):
        self.host=Host("localhost", "boby", "098334057")
        
    def tearDown(self):
        pass
    
    def testCheckHost(self):
        self.host.checkHost()
        self.assertTrue(self.host.getStatus() in [Host.States.Available, Host.States.Down], "CheckHost function failed")
        
    def testErrors(self):
        self.host.checkHost()
        self.host.setMaxErrors(1)
        self.host.addError()
        self.assertTrue(self.host.getStatus() == Host.States.Error, "Host errors are not the expected status!!!")
        self.host.resetErrors()
        
    def testaddProcess(self):
        self.host.checkHost()
        self.host.setMaxProcess(2)
        self.host.addProcess()
        self.assertTrue(self.host.getStatus() == Host.States.Running, "Host process are not reported!!!")
        
    def testdelProcess(self):
        self.host.checkHost()
        self.host.setMaxProcess(2)
        self.host.addProcess()
        self.host.delProcess()
        self.assertTrue(self.host.getStatus() == Host.States.Available, "Host process are not reported!!!")
        
    def testfullProcess(self):
        self.host.checkHost()
        self.host.setMaxProcess(1)
        self.host.addProcess()
        self.assertTrue(self.host.getStatus() == Host.States.Full, "Host process are not reported!!!")
    
    def testdelfromFullProcess(self):
        self.host.checkHost()
        self.host.setMaxProcess(2)
        self.host.addProcess()
        self.host.addProcess()
        self.host.delProcess()
        self.assertTrue(self.host.getStatus() == Host.States.Running, "Host process are not reported!!!")
Exemplo n.º 29
0
#!/usr/bin/python
import sys, time
from IOS import *
from Util import *
from Host import Host

h = Host("sqa05")
h.logon()
device = "/dev/vgcc"
device_p = device + "0"
sec_opt = sys.argv[1]
dir = "/flash_max/"

#print "Please do reset card, press any key to continue.."
#raw_input()
#h.reset_card(device)
#wait = 60

#h.create_and_verify_fs(device_p,"ext3")
h.rmdir(dir)
h.mkdir(dir)
h.mount_fs(device_p, dir)
h.cp_dict(dir)
sys.exit(1)

h.mount_fs("/dev/vgcc0", "/flash_max")
sys.exit(1)
print "Wating %i secs after resettting the card" % wait
for i in range(wait):
    print "Seconds Passed \r %d" % i,
    sys.stdout.flush()
Exemplo n.º 30
0
#!/usr/bin/python
import sys,time
from Host import Host
from Util import *
from Trace import *

file = "del"
f = open(file,"w")
h = Host("sqa05",logfile_object = f)
#h.reset_card("/dev/vgca")
#h.run_vgc_monitor("/dev/vgca")


#h.connection.interact()
#h.get_ipmi_ip_addr()

device = sys.argv[1]
dev_p = device + "0"
#expected_mode = "maxperformance"
expected_mode = "maxcapacity"
expected_usable_cap = "702"

usable_cap = h.get_part_usable_cap(device)[dev_p]['us_cap']
mode = h.get_part_mode(dev_p)
serial = h.get_card_serial(device)
card_info = h.get_card_info(device)
kernel = h.get_kernel_ver()
redhat_ver = h.cat_etc_issue()

sec_er = sys.argv[2]
trace_info("-" * 80)
Exemplo n.º 31
0
import sys
import random
from Host import Host

if __name__ == '__main__':
    random.seed()
    host = Host(sys.argv[1],
                sys.argv[2],
                frame_transf_interv=3,
                inter_frame_gap=1,
                min_frame_gap=3,
                max_frame_gap=8)
    host.run()
Exemplo n.º 32
0
	def initHost(ip):
		host = Host(ip)
		print(ip)
		host.getInterfaces()
		host.hasBridge()
		return host
Exemplo n.º 33
0
#!/usr/bin/python
import sys, time
from IOS import *
from Host import Host
from Trace import *

h = Host("sqa05")
h.logon()
device = "/dev/vgcc"
device_p = device + "0"
sec_opt = sys.argv[1]

print_blue("-" * 80)
trace_info(" Starting fill drive test on device '%s', option '%s'" %
           (device, sec_opt))
print_blue("-" * 80)
#print "Please do reset card, press any key to continue.."
#raw_input()
h.reset_card(device)
wait = 60
print "Wating %i secs after resettting the card" % wait
for i in range(wait):
    sec_rem = wait - i
    print "Seconds Passed \r %d" % sec_rem,
    sys.stdout.flush()
    time.sleep(1)

h.run_command("vgc-monitor -d %s" % device)
io = DD(h)

Exemplo n.º 34
0
 def GetServer(self):
     if not hasattr(self, "server_obj"):
         self.server_obj = Host(self.server, self.Logger)
     return self.server_obj
Exemplo n.º 35
0
 def GetClient(self):
     if not hasattr(self, "client_obj"):
         self.client_obj = Host(self.client, self.Logger)
     return self.client_obj
Exemplo n.º 36
0
def addHost():
    hostQueue = Queue()
    name = input("Enter the name of the host in Single Capital Letter")
    host = Host(hostQueue, "Active", name)
    toHostConnectionObject, portNo = host.toHostPipe()
    NETWORK_Connection_Register[0].append((name, host, toHostConnectionObject))
Exemplo n.º 37
0
from flask import Flask, render_template, request, jsonify, json
from Player import Player
from Game import Game
from Host import Host
from Block import Block

app = Flask(__name__)
host = Host()


def _steer_round(data, start=False):
    game = host.find_game(data.get('gameKey'))
    player = game.find_player(player_key=data.get('playerKey'))
    if host.check_instance(game, Game) and host.check_instance(player, Player):
        round_data = host.menage_round(start=start, target_game=game)
        data = {'roundData': round_data}
        if start:
            player.drew_block = False
            data['drewBlock'] = player.drew_block
        return jsonify(data)
    return jsonify({'errors': 'failed to change round status'})


@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')


# data: gameType = 'multiplayer'/'singleplayer'/'localgame',  gameName = str/None, gamePassword = str/None founderName = str,  slots = 1<int<5, founderType = 'net'/'local'
# return: gameData = {state, key, kasPassword, type, name, slots, playersData, winner}, founderData = {name, type, key, gameKey, hasCleanSet, gotBlocks}
@app.route('/create-game', methods=['POST'])
Exemplo n.º 38
0
 def __init__(self, name, info, logger):
     self.name = name
     self.info = info
     self.pids = []
     self.host = Host(info[0], logger)
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 25 23:51:37 2013

@author: Alejandro
"""
import Pyro4
from Agente import Agente
from Servicio import Servicio
from ComunidadAgentes import ComunidadAgentes
from Host import Host



HostLogik = Host("Logik")
#Metodo pyro
#Se crea de la manera simple con serveSimple, sin tener en cuenta el host.
Pyro4.Daemon.serveSimple({
    HostLogik : "host." + str(HostLogik.getNombre())
},host="0.0.0.0")

Exemplo n.º 40
0
 def setUp(self):
     self.host=Host("localhost", "boby", "098334057")
Exemplo n.º 41
0
class Palette():
    
    
    def __init__(self):
        self.case1=None
        self.case2=None
        self.case3=None
        self.case4=None
        self.case5=None
        self.element1=None
        self.element2=None
        self.element3=None
        self.element4=None
        self.button_exit=None
        self.button_next=None
        self.Bus1=None
        self.Bus2=None
        self.case11=pygame.image.load("Images/Case1.1.jpg")
        self.case12=pygame.image.load("Images/Case1.2.jpg")
        self.case21=pygame.image.load("Images/Case2.1.jpg")
        self.case22=pygame.image.load("Images/Case2.2.jpg")
        self.case31=pygame.image.load("Images/Case3.1.jpg")
        self.case32=pygame.image.load("Images/Case3.2.jpg")
        self.case41=pygame.image.load("Images/Case4.1.jpg")
        self.case42=pygame.image.load("Images/Case4.2.jpg")
        self.case51=pygame.image.load("Images/Case5.1.jpg")
        self.case52=pygame.image.load("Images/Case5.2.jpg")
        self.exit1=pygame.image.load("Images/button_exit1.jpg")
        self.exit2=pygame.image.load("Images/button_exit2.jpg")
        self.next1=pygame.image.load("Images/button_next1.jpg")
        self.next2=pygame.image.load("Images/button_next2.jpg")
        self.createPalette()
        self.display=pygame.display.get_surface()
    
    def updatePalette(self):
        x,y=pygame.mouse.get_pos()
        if(self.case1.rect.collidepoint(x,y)):
            self.case1.image=self.case12
        else:
            self.case1.image=self.case11
            
        if(self.case2.rect.collidepoint(x,y)):
            self.case2.image=self.case22
        else:
            self.case2.image=self.case21
            
        if(self.case3.rect.collidepoint(x,y)):
            self.case3.image=self.case32
        else:
            self.case3.image=self.case31  
        if(self.case4.rect.collidepoint(x,y)):
            self.case4.image=self.case42
        else:
            self.case4.image=self.case41  
        if(self.case5.rect.collidepoint(x,y)):
            self.case5.image=self.case52
        else:
            self.case5.image=self.case51 
        if(self.button_exit.rect.collidepoint(x,y)):
            self.button_exit.image=self.exit2
        else:
            self.button_exit.image=self.exit1
        if(self.button_next.rect.collidepoint(x,y)):
            self.button_next.image=self.next2
        else:
            self.button_next.image=self.next1      
        
        self.display.blit(self.case1.image,self.case1.rect)
        self.display.blit(self.case2.image,self.case2.rect)
        self.display.blit(self.case3.image,self.case3.rect)
        self.display.blit(self.case4.image,self.case4.rect)
        self.display.blit(self.case5.image,self.case5.rect)
        self.display.blit(self.button_exit.image,self.button_exit.rect)
        self.display.blit(self.button_next.image,self.button_next.rect)
        
        rect=pygame.Rect(160, 0, 10,1000)
        pygame.draw.rect(self.display,(220,0,0),rect,0)
        
        myfont = pygame.font.SysFont("LCD", 75)
        label = myfont.render("ARP SIMULATOR", 1,(220,0,0))
        self.display.blit(label, (500, 15))
        
    def createCase1(self):
        self.element1=Host(300,200,0,0)
        self.element2=Host(900,200,0,0)
        self.Bus1=Bus(300,205,900,205)
        #self.arp_request.rect.left,self.arp_request.rect.top=300,200
        
    def createCase2(self):
        self.element1=Host(300,200,0,0)
        self.element2=Router(900,200,0,0)
        self.Bus1=Bus(300,205,900,205)
        
    def createCase3(self):
        self.element1=Router(300,200,0,0)
        self.element2=Router(900,200,0,0)
        self.Bus1=Bus(300,205,900,205)
    
    def createCase4(self):
        self.element1=Router(300,200,0,0)
        self.element2=Host(900,200,0,0)
        self.Bus1=Bus(300,205,900,205)
        
    def createCase5(self):
        self.element1=Host(300,200,0,0)
        self.element2=Host(1000,200,0,0)
        self.element3=Router(650,200,0,0)
        self.element4=Host(650,400,0,0)
        self.Bus1=Bus(300,205,1000,205)
        self.Bus2=Bus(660,200,660,400)
           
    def update(self,screen):  
        self.Bus1.drawpoint(screen)
        self.element1.update(screen,1)
        self.element2.update(screen,1)
    
    def update5(self,screen):
        self.Bus1.drawpoint(screen)
        self.Bus2.drawpoint(screen)
        self.element1.update(screen,1)
        self.element2.update(screen,1)
        self.element3.update(screen,1)
        self.element4.update(screen,1)
        
    def createSprite(self,x,y,adr):
        s1 = pygame.sprite.Sprite()
        s1.image = pygame.image.load(adr).convert_alpha()
        s1.rect = s1.image.get_rect()
        (s1.rect.left, s1.rect.top) = (x,y)
        return s1   
    
    def createPalette(self):
        self.case1=self.createSprite(10,40,"Images/Case1.1.jpg")
        self.case2=self.createSprite(self.case1.rect.left,self.case1.rect.bottom+20,"Images/Case2.1.jpg")
        self.case3=self.createSprite(self.case2.rect.left,self.case2.rect.bottom+20,"Images/Case3.1.jpg")
        self.case4=self.createSprite(self.case3.rect.left,self.case3.rect.bottom+20,"Images/Case4.1.jpg")
        self.case5=self.createSprite(self.case4.rect.left,self.case4.rect.bottom+20,"Images/Case5.1.jpg")
        self.button_exit=self.createSprite(1200, 5,"Images/button_exit1.jpg")
        self.button_next=self.createSprite(1200, 670,"Images/button_next1.jpg")
        
    def ARPDesign(self,screen):
        c1 = pygame.time.Clock()
        Case1Pressed=False
        Case2Pressed=False
        Case3Pressed=False
        Case4Pressed=False
        Case5Pressed=False
        flag=True
        while True and flag:
            for events in pygame.event.get():
                    if events.type == pygame.QUIT:
                        quit()
                    if events.type == pygame.MOUSEBUTTONDOWN:
                        x,y=pygame.mouse.get_pos()
                        if(self.case1.rect.collidepoint(x,y) and not(Case1Pressed)):
                            Case1Pressed=True
                            Case2Pressed=False
                            Case3Pressed=False
                            Case4Pressed=False
                            Case5Pressed=False
                            self.createCase1()
                        if(self.case2.rect.collidepoint(x,y)):
                            Case1Pressed=False
                            Case2Pressed=True
                            Case3Pressed=False
                            Case4Pressed=False
                            Case5Pressed=False
                            self.createCase2()
                        if(self.case3.rect.collidepoint(x,y)):
                            Case1Pressed=False
                            Case2Pressed=False
                            Case3Pressed=True
                            Case4Pressed=False
                            Case5Pressed=False
                            self.createCase3()
                        if(self.case4.rect.collidepoint(x,y)):
                            Case1Pressed=False
                            Case2Pressed=False
                            Case3Pressed=False
                            Case4Pressed=True
                            Case5Pressed=False
                            self.createCase4()
                        if(self.case5.rect.collidepoint(x,y)):
                            Case1Pressed=False
                            Case2Pressed=False
                            Case3Pressed=False
                            Case4Pressed=False
                            Case5Pressed=True
                            self.createCase5()
                        if(self.button_next.rect.collidepoint(x,y)):
                            flag=False
                        if(self.button_exit.rect.collidepoint(x,y)):
                            flag=False
                            return 0
                        
                              
            c1.tick(100)
            screen.fill((255,255,255))
            self.updatePalette()
            if(Case1Pressed or Case2Pressed or Case3Pressed or Case4Pressed):
                self.update(screen)
            if(Case5Pressed):
                self.update5(screen)
            pygame.display.update()
        if(Case1Pressed):
            return 1
        if(Case2Pressed):
            return 2
        if(Case3Pressed):
            return 3
        if(Case4Pressed):
            return 4
        if(Case5Pressed):
            return 5
Exemplo n.º 42
0
def scrap(params):
    """
    Make the scrap for the params in script.py
    :param params: the param dictionnary
    :return: None
    """

    print("Starting to scrap data...")

    f = open(params["output_file"], 'w')

    # We display the header
    for column in params["list_columns"]:
        f.write('%s\t' % column)
    f.write('\n')

    soup_list = Host.get_soup_list()
    if soup_list is None:
        print("Can't get the list of all host.")
        exit(1)
    rows = soup_list.find_all('tr', "sectiontableentry1") + soup_list.find_all('tr', "sectiontableentry2")

    cpt = 0
    size = len(rows)
    qty_matched = 0
    failed = []
    start = time.time()

    for row in rows:
        if cpt > 10:
            break
        # We use the cpt to know at wich percent we are
        percent = (cpt / size) * 100
        if params["display_eta"] and cpt % 5 == 0:
            eta = get_eta(start, percent)
            print("%.2f%% ETA : %s" % (percent, eta))
        cpt += 1

        # We get the soup for the current item
        item_id = row.contents[1].contents[1].contents[0].contents[0]

        host = Host(item_id)
        if not host.isValid:
            failed.append(item_id)
            continue

        should_add = host.should_add(params["criterias"])

        if should_add:
            host_as_string = host.to_string(params["list_columns"])

            # We output the result
            f.write('%s\n' % host_as_string)
            qty_matched += 1

    print("From the %s hosts, there is %s that match the criterias" % (size, qty_matched))
    if len(failed) > 0:
        print("The following hosts page didn't answered in time. They can't be listed : \n%s" % failed)
        f.write('%s\n' % failed)

    f.close()
    def initialize(self):
        Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle')
        #Prueba
        nombre = "Logik"

		#Se obtiene la ip de la red.
        mi_ip = Pyro4.socketutil.getIpAddress(None, workaround127=True)

        try:
            ns = Pyro4.locateNS(host = mi_ip)
            print("Existe un servidor de NS.")
            self.ready = True
        except:
            
		    #Al activarse la bandera no se seguira tratando de obtener el host en vez de esto se creara.
		    banderaNS = True
		    banderaHost = True

		    try:
		        ns = Pyro4.locateNS()
		    except: 
		        print("No existe un servidor de NS.")
		        banderaNS = False
		        banderaHost = False


		    if(banderaNS):
		        try:
		            hostNS = Pyro4.core.Proxy("PYRONAME:" + ns.list().keys()[1])
		        except:
		            print("No existe un host en este servidor de NS.")
		            banderaHost = False

		    

		    print("Se procedera a crear un host")
		    hostDemonio = Host(nombre)


		    if(banderaHost):
		        print("Se obtendra una lista de los ns")
		        hostDemonio.setListNS(hostNS.getListNS())




		    print("Inicializando servicios... tipo de servidor=%s" % Pyro4.config.SERVERTYPE)
		    # start a name server with broadcast server as well
		    nameserverUri, nameserverDaemon, broadcastServer = Pyro4.naming.startNS(host="0.0.0.0")
		    assert broadcastServer is not None, "excepcion no se ha podido crear el servidor de broadcast"

		    print("Obteniendo el nombre del servidor o nameserver (ns), uri=%s" % nameserverUri)
		    print("Localizacion del demonio ns string=%s" % nameserverDaemon.locationStr)
		    print("Demonio de socket ns=%s" % nameserverDaemon.sockets)
		    print("Demonio de socket bc=%s (fileno %d)" % (broadcastServer.sock, broadcastServer.fileno()))
		       
		    if(banderaHost):    
		        for nameServer,nameServer_uri in hostNS.getListNS().items():
		            nsDisperso = Pyro4.Proxy(nameServer_uri)
		            for host, hostDisperso_uri in nsDisperso.list(prefix="host.").items():
		                hostDisperso = Pyro4.Proxy(hostDisperso_uri) 
		                hostDisperso.addNS(mi_ip, nameserverUri)
		        
		    hostDemonio.addNS(mi_ip, nameserverUri)

		                
		    #Metodo pyro
		    #Crear un demonio en pyro
		    pyrodaemon=Pyro4.core.Daemon(host=mi_ip)
		    print("Localizacion del demonio str=%s" % pyrodaemon.locationStr)
		    print("Socket del demonio=%s" % pyrodaemon.sockets)
		    # Se registrara un demonio en el servidor de objetos
		    serveruri=pyrodaemon.register(hostDemonio)
		    print("URI del server=%s" % serveruri)
		    host_proxy = Pyro4.Proxy(serveruri)

		    # Se registrara el demonio con el servidor embebido 
		    nameserverDaemon.nameserver.register("host." + nombre,serveruri)  

		    verificacionDeTiempo = time.time()
		       
		       

		    # Se crea un loop para los demonios customizado
		    while self.running:
		        self.ready=True
		        try:
		            if(time.time()-verificacionDeTiempo >= 120):
		                #Verificar conexion con host
		                listNS = hostDemonio.getListNS().copy()
		                listNS.pop(mi_ip)
		                for host_iter,host_iter_uri in listNS.items():    
		                    locationHost = Pyro4.URI(host_iter_uri).location
		                    remoteDeamon = Pyro4.Proxy('PYRO:' + Pyro4.constants.DAEMON_NAME + '@' + locationHost)
		                    try:
		                        remoteDeamon.ping()
		                    except:
		                        print "Se ha perdido la conexion con: " + locationHost
		                        hostDemonio.deleteNS(locationHost[:locationHost.find(":")])
		                        print "prueba"
		                print "1"
		                verificacionDeTiempo = time.time()
		                print "2"
		                    
		                        
		            #Verificar 
		            
		            
		            
		            
		            print("Esperando por eventos...")
		            # crear un conjuto de sockets, por los cuales se estara esperando 
		            # (un conjuto que provee una lista rapiada para ser comparada)
		            nameserverSockets = set(nameserverDaemon.sockets)
		            pyroSockets = set(pyrodaemon.sockets)
		            # Solo el broadcast server es dicretamente usable como un select() objeto
		            # select() se usa como un comando que espera hasta que una entrada llegue
		            # esta entrada puede ser bien una entrada de IO rw, r,rw+
		            rs=[broadcastServer]  
		            rs.extend(nameserverSockets)
		            rs.extend(pyroSockets)
		            rs,_,_ = select.select(rs,[],[],3)
		            eventsForNameserver=[]
		            eventsForDaemon=[]
		            for s in rs:
		                if s is broadcastServer:
		                    print("Servidor de Broadcast recibio una solicitud")
		                    broadcastServer.processRequest()
		                elif s in nameserverSockets:
		                    eventsForNameserver.append(s)
		                elif s in pyroSockets:
		                    eventsForDaemon.append(s)
		            if eventsForNameserver:

		                print("Nameserver recibio una solicitud")
		                nameserverDaemon.events(eventsForNameserver)
		            if eventsForDaemon:
		                print("Demonio Host recibio una solicitud")
		                pyrodaemon.events(eventsForDaemon)
		                
		        except:
		            print "Ha ocurrido una excepcion"

		    nameserverDaemon.close()
		    broadcastServer.close()
		    pyrodaemon.close()
		    print("done")
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.background_image = tk.PhotoImage(file = '../Backgrounds/hostclient_background.png')
        self.background = tk.Label(self, borderwidth=0, highlightthickness=0, image = self.background_image)
        self.background.place(x=0, y=0)

        self.back_button_image = tk.PhotoImage(file = '../Graphics/back_button.png')
        self.back_button = tk.Button(self, activebackground='black', image = self.back_button_image, command=lambda: controller.show_frame("Menu"))
        self.back_button.place(x=1000, y=600)

        self.host_image = tk.PhotoImage(file = '../Graphics/host.png')
        self.host = tk.Button(self, activebackground='black', image = self.host_image, command=lambda: [controller.show_frame("ConnectingHostPage"), Host.connecting()])
        self.host.place(x=268, y=180)

        self.client_image = tk.PhotoImage(file = '../Graphics/client.png')
        self.client = tk.Button(self, activebackground='black', image = self.client_image, command=lambda: [controller.show_frame("ConnectingClientPage"), Client.connecting()])
        self.client.place(x=630, y=180)
import sys
import random
from Host import Host


if __name__ == '__main__':
     random.seed()
     host = Host(sys.argv[1],sys.argv[2], min_frame_gap=3 , max_frame_gap=8)
     host.run()
Exemplo n.º 46
0
def GetHost(options):
    if options.test: return GetHostStub(options.hostname)
    else: return Host.GetHost(optionsParser.GetConnectSpec(options))
Exemplo n.º 47
0
    def generatgeView(self,rHosts,subnetSpace,targetPort,NCDSPort,HoneyPort,numSubnets,minHP,maxHP,Strategy):

        self.targetsubnet = numSubnets
        self.lowerSubnet = numSubnets/2
        self.upperSubnet = 0
        #generate specified number of subnets
        for s in range(1,numSubnets):
            self.getAvaiSubnet(numSubnets)

        hosts=[]
        #assign hosts to subnets, and deceive their data
        for k in rHosts.keys():
            if k!=NCDSPort and k!=HoneyPort:
                #create new host object
                realip=rHosts[k].split("/")[0]
                realmac=rHosts[k].split("/")[1]
                if k==targetPort:
                    self.target=Host(self.getShortnameHost(),realip,realmac,k)
                    #get subnet address for target
                    self.target=self.setAvailableSubnetAddress(subnetSpace,numSubnets,self.target,targetPort)
                    #print(str(self.target.deceptiveIP))
                else:
                    host=Host(self.getShortnameHost(),realip,realmac,k)
                    #get subnet address for host
                    host=self.setAvailableSubnetAddress(subnetSpace,numSubnets,host,targetPort)
                    #print(str(host.deceptiveIP))

        #assign honeypots to subnets
        realHoneyIP=rHosts[HoneyPort].split("/")[0]
        realHoneyMac=rHosts[HoneyPort].split("/")[1]
        for subKey in self.subnetList.keys():
            numHoneypots=random.randint(minHP,maxHP)
            for hp in range(1,numHoneypots):
                subnet=self.subnetList[subKey]
                hpAddr=self.getAvaiHoneypotforSubnet(subnet)
                honeyAddr=str(subnetSpace[:-2]) + "." + str(subnet.number) + "." + str(hpAddr)
                honeypot=Honeypot(self.getShortnameHoneypot(),realHoneyIP,realHoneyMac,honeyAddr,self.randMac(),HoneyPort)
                self.subnetList[subnet.number].honeypots.append(honeypot)
                #print("Honeypot " + honeyAddr)

        #create honeyrouters
        routerMac=self.randMac()
        targetSubnet = int(self.target.deceptiveIP.split(".")[2])

        subnet=self.subnetList[targetSubnet]
        subnetAddr=str(subnetSpace[:-2]) + "." + str(subnet.number) + ".1"
        hr=Honeyrouter(self.getShortnameHoneyrouter(),subnetAddr,routerMac,NCDSPort)
        subnet.honeyrouter.append(hr)
        gateway=hr.shortName
        self.subnetList[subnet.number]=subnet
        self.honeyrouterList.append(hr)

        for subKey in self.subnetList.keys():
            subnet=self.subnetList[subKey]
            if subnet.number != targetSubnet:
                subnetAddr=str(subnetSpace[:-2]) + "." + str(subnet.number) + ".1"
                hr=Honeyrouter(self.getShortnameHoneyrouter(),subnetAddr,routerMac,NCDSPort)
                subnet.honeyrouter.append(hr)
                self.subnetList[subKey]=subnet
                self.honeyrouterList.append(hr)



        #generate routes
        numhops=1
        for subKey in self.subnetList.keys():
            subnet=self.subnetList[subKey]
            targetSubnet = int(self.target.deceptiveIP.split(".")[2])

            if subnet.number != targetSubnet:
                numhops+=1
                #numhops=random.randint(2,networkDiameter)
                hostIdx=0
                for host in subnet.hosts:
                    r=Route(self.target,host)
                    hostSubnet = int(host.deceptiveIP.split(".")[2])
                    #hops = int(math.fabs(hostSubnet-targetSubnet))

                    #max sub dist min hop dist
                    if Strategy=="minhop_maxsub":
                        hops = numSubnets - hostSubnet

                    if Strategy=="maxhop_maxsub":
                    #max sub dist max hop dist
                        hops = hostSubnet

                    for hop in range(0,hops):
                        r.addHop(self.honeyrouterList[hop])
                    self.routeList.append(r)
                    host.distance=hops
                    #subnet.hosts.insert(hostIdx,host)
                    #hostIdx+=1
                for honeypot in subnet.honeypots:
                    r=Route(self.target,honeypot)
                    for hop in range(0,numhops-1):
                        r.addHop(self.honeyrouterList[hop])
                    self.routeList.append(r)
            else:
                for host in subnet.hosts:
                    r=Route(self.target,host)
                    self.routeList.append(r)
                for honeypot in subnet.honeypots:
                    r=Route(self.target,honeypot)
                    self.routeList.append(r)

        #set gateway


        printer = NetworkPrinter()
        realhosts = printer.printView(self.target,self.subnetList,self.routeList,targetPort,gateway)
        #for printhost in realhosts:
            #print("realhosts.append(\"" + printhost + "\")")
        return (realhosts, self.targetsubnet)