Example #1
0
def option1():
    global ipsrc, ipdst
    iplist = []
    os.system("clear")
    a = 1
    print "Network interfaces & IPs"
    print "------------------------"
    for i in interfaces.interfaces():
        print "%d. Interface name: " % a, i, ", IP: ", interfaces.interfaces()[i]
        iplist.append(interfaces.interfaces()[i])
        a+=1
    while True:
        out_int = raw_input("Output interface: ")
        try:
            ipsrc = iplist[int(out_int)-1]
            break
        except IndexError:
            print "Try again!"
    while True:
        in_int = raw_input("Input interface: ")
        if out_int <> in_int:
            try:
                ipdst = iplist[int(in_int) - 1]
                break
            except IndexError:
                print "Try again!"
        else:
            print "Try again!"
    print "________________________________________________________________\n"
    print "Source IP: ",ipsrc,"\n","Destination IP: ", ipdst
    raw_input("\nPress enter to return to main menu...")
Example #2
0
    def __init__(self, dst=None):
        # Get one's SRC IP & interface
        i = interfaces.interfaces()
        self.src = i[1][0]
        self.iface = i[0]
        self.netmask = i[1][1]
        self.enet = i[2]
        self.dst = dst
        sys.stderr.write("SIP IP %s, iface %s, netmask %s, enet %s\n" %
                         (self.src, self.iface, self.netmask, self.enet))
        # A queue where received packets go.  If it is full
        # packets are dropped.
        self.packetQueue = Queue.Queue(100000)
        self.dropCount = 0
        self.idcount = 0

        self.ethrdst = ""

        # Get the destination ethernet address with an ARP
        self.arp()

        # You can add other stuff in here to, e.g. keep track of
        # outstanding ports, etc.

        # Start the packet sniffer
        t = threading.Thread(target=self.run_sniffer)
        t.daemon = True
        t.start()
        time.sleep(.1)
Example #3
0
def main():
    """
    Execution begins here.
    """
    ints = interfaces.interfaces()

    # Add Ethernet0/1, enable it, and place into VLAN 10
    eth01 = ints.interface_container.switchport_list.add("Ethernet0/1")
    eth01.enabled = True
    eth01.vlan = 10

    # Add Ethernet0/2, enable it, and place into VLAN 20
    eth02 = ints.interface_container.switchport_list.add("Ethernet0/2")
    eth02.enabled = True
    eth02.vlan = 20

    # Add Ethernet0/3, but try and set VLAN to 9999
    eth03 = ints.interface_container.switchport_list.add("Ethernet0/3")
    try:
        print("Trying to set bogus VLAN 9999")
        eth03.vlan = 9999
    except ValueError as exc:
        # This code always runs, since VLAN 9999 is never valid
        print(exc.args[0]["error-string"])

    # Add Loopback0, enable it, and set an IP address
    lb0 = ints.interface_container.virtual_list.add("Loopback0")
    lb0.enabled = True
    lb0.ip_address = "192.0.2.1"

    # Add Loopback1, but leave all default values in place
    lb1 = ints.interface_container.virtual_list.add("Loopback1")

    # Print JSON representation of the current config
    print(json.dumps(ints.get(), indent=2))
Example #4
0
 def __init__(self,basedir=".",mode="initial",cores=-1):
     self.basedir = basedir
     self.mode = mode
     self.lastAcceptedPath = "start"
     if cores == -1:
         self.cores = multiprocessing.cpu_count()
     else:
         self.cores = cores
     self.wrapper = wrappers.gromacswrapper()
     self.distparser = parser.gdistparser()
     self.filesystem = filesystem.filesystem()
     self.interfaces = interfaces.interfaces()
     self.stablestates = stablestates.stablestates()
     self.helper = helpers.helpers()
     #Initialize the logger
     self.log = gtpslogging.log("debug",basedir)
     self.log.log.debug("logfile created")
     self.log.log.info(str(self.cores) + " CPUs detected")
     
     #read the stables states from a file
     self.stablestates.readStates(os.path.join(basedir,"stablestates.txt"))
     self.log.log.info("Read States : " + str(self.stablestates.states))
     
     """
     This array holds all the information about the paths. Each trajectory consists of a 
     forward-part and a backward-part. The trajectory can either be a forward trajectory
     or a backward trajectory. Forward trajectroies start in A.
     """
     self.paths = []
     self.paths.append(pathsimulation.pathdata(0,basedir,mode,forward=True,forwardpart=True))
     self.paths.append(pathsimulation.pathdata(0,basedir,mode,forward=True,forwardpart=False))
Example #5
0
def main():
	mainLogger = logger.logger("main")
	mainLogger.log.info("Starting main")

	mainInterfaces = interfaces.interfaces()
	openInterfaces(mainInterfaces)

	mainDataManager = dataManager.dataManager(interfaces=mainInterfaces)


	######## GENERATE FAKE DATA DONT FORGET TO REMOVE THIS #####################
	# mainDataManager.genFakeData()
	############################################################################


	axLogPath = "/logs/axlisten.log"
	ground = groundComms.groundComms(axLogPath=axLogPath, interfaces=mainInterfaces, dataManager=mainDataManager)

	mainInterfaces.gpio.setPinMode(pin=18, mode=mainInterfaces.gpio.OUTPUT) # Status LED

	# Schedule tasks
	mainScheduler = scheduler.scheduler()
	mainScheduler.schedule(callback=mainDataManager.setTimeSync, frequency=20)
	mainScheduler.schedule(callback=mainDataManager.log, frequency=3)
	mainScheduler.schedule(callback=ground.streamTelemetry, frequency=10)
	mainScheduler.schedule(callback=mainInterfaces.habip_osd.cycle, frequency=20)

	# Set OSD header because fun
	header = "{} RIT TEAM HABIP {}".format(mainInterfaces.osd232.symbol["satellite"], mainInterfaces.osd232.symbol["heart"])
	mainInterfaces.habip_osd.header = header

	run = True
	while run:

		mainInterfaces.watchdog.pet() # Pet the watchdog
		mainInterfaces.gpio.toggleOutput(18) # Status LED

		ground.update()
		ground.executeCommands(withDelay=100)

		mainDataManager.update()
		mainInterfaces.daqcs.update()
		mainScheduler.update()

		mainInterfaces.habip_osd.update_all() # This takes about a second to process

		# print mainInterfaces.habip_osd.osd232.preview()

		# for name, board in mainInterfaces.boards.iteritems():
		# 	print "Data for board: {}".format(name)
		# 	board.printAllData()

	mainLogger.log.info("main loop terminating")
Example #6
0
 def __init__(self, api_key, api_url, local_hostname, configured_interfaces):
     """Initialize dnsupdate"""
     # Pull configuration from config_settings
     self.api_key = api_key
     self.local_hostname = local_hostname
     self.configured_interfaces = configured_interfaces
     self.interface = interfaces.interfaces(self.configured_interfaces)
     self.prev_addresses = [ ipaddress.ip_address('127.0.0.1'), ipaddress.ip_address('::1') ]
     # Set up http_accessor object.
     try:
         self.dreamhost_accessor = http_access.http_access(api_url)
     except KeyError as error:
         logging.critical("Could not set up DreamHost API communications. Error:  %s" % (error))
Example #7
0
 def __init__(self, api_key, api_url, local_hostname, configured_interfaces):
     """Initialize dnsupdate"""
     # Pull configuration from config_settings
     self.api_key = api_key
     self.local_hostname = local_hostname
     self.configured_interfaces = configured_interfaces
     self.interface = interfaces.interfaces(self.configured_interfaces)
     self.prev_addresses = [ ipaddress.ip_address('127.0.0.1'), ipaddress.ip_address('::1') ]
     # Set up http_accessor object.
     try:
         self.dreamhost_accessor = http_access.http_access(api_url)
     except KeyError as error:
         logging.critical("Could not set up DreamHost API communications. Error:  %s" % (error))
Example #8
0
 def __init__(self, api_key, api_url, local_hostname, configured_interfaces, bExternal, external_url, previous_v4_address, previous_v6_address):
     """Initialize dnsupdate"""
     # Pull configuration from config_settings
     self.api_key = api_key
     self.local_hostname = local_hostname
     self.configured_interfaces = configured_interfaces
     self.use_external = bExternal
     self.interface = interfaces.interfaces(self.configured_interfaces)
     self.previous_v4_address = ipaddress.ip_address(previous_v4_address)
     self.previous_v6_address = ipaddress.ip_address(previous_v6_address)
     self.prev_addresses = [ self.previous_v4_address, self.previous_v6_address ]
     
     if self.use_external:
         if logging.getLogger().getEffectiveLevel() == logging.INFO:
             logging.getLogger("requests").setLevel(logging.WARNING)
             
         try:
             response = requests.request('GET', external_url)
             if response.status_code == 200:
                 self.external_ip = ipaddress.ip_address(response.text)
                 if self.external_ip.version == 4:
                     logging.info("External IP address detected as: %s" % (self.external_ip))
                 else:
                     logging.critical("Error retrieving external IP.  Response:  %s" % (response.text))
                     sys.exit()
             else:
                 logging.critical("Could not access external url. Status code: %s" % (response.status_code))
                 sys.exit()
         except:
             logging.critical("Could not access external url: %s" % (external_url))
             sys.exit()
         
         if logging.getLogger().getEffectiveLevel() == logging.INFO:
             logging.getLogger("requests").setLevel(logging.getLogger().getEffectiveLevel())
         
     # Set up http_accessor object.
     try:
         self.dreamhost_accessor = http_access.http_access(api_url)
     except KeyError as error:
         logging.critical("Could not set up DreamHost API communications. Error:  %s" % (error))
         sys.exit()
Example #9
0
 def __init__(self, dst=None):
     # get source ip and interface
     i = interfaces.interfaces()
     self.src = i[1][0]
     self.iface = i[0]
     self.netmask = i[1][1]
     self.enet = i[2]
     self.dst = dst
     sys.stderr.write("SIP IP %s, iface %s, netmask %s, enet %s\n" %
                      (self.src, self.iface, self.netmask, self.enet))
     # packet queue
     self.packetQueue = Queue.Queue(100000)
     self.dropCount = 0
     self.idcount = 0
     self.ethrdst = ""
     # arp request for the address
     self.arp()
     # Start the packet sniffer
     t = threading.Thread(target=self.run_sniffer)
     t.daemon = True
     t.start()
     time.sleep(.1)
Example #10
0
def main():

    intf = interfaces.interfaces()
    intf.openspi()
    intf.opendaqcs()

    d = intf.daqcs

    while True:
        print "----------"
        print d.currentState

        # d.queueCommand("{06:1491592543}")
        # d.queueCommand("{05:B0}")
        # d.queueCommand("{06:1491592543}")
        d.update()

        for name, board in intf.boards.iteritems():
            print "Data for board: {}".format(name)
            board.printAllData()

        common.msleep(3000)
Example #11
0
def main():
    ints = interfaces.interfaces()

    eth01 = ints.interface_container.switchport_list.add("Ethernet0/1")
    eth01.enabled = True
    eth01.vlan = 10
    eth02 = ints.interface_container.switchport_list.add("Ethernet0/2")
    eth02.enabled = True
    eth02.vlan = 10
    eth03 = ints.interface_container.switchport_list.add("Ethernet0/3")
    try:
        print("Trying to set bogus VLAN 9999")
        eth03.vlan = 9999
    except ValueError as exc:
        print(exc.args[0]['error-string'])

    lb0 = ints.interface_container.virtual_list.add("Loopback0")
    lb0.enabled = True
    lb0.ip_address = "192.0.2.1"

    lb1 = ints.interface_container.virtual_list.add("Loopback1")

    print(json.dumps(ints.get(), indent=2))
Example #12
0
#!/usr/bin/env python

import axreader
import interfaces
import common
import groundComms

################################# Unit Testing #################################
if __name__ == "__main__":

    LOG_PATH = "/home/pi/axlisten.log"

    i = interfaces.interfaces()
    i.openbeacon()

    gc = groundComms.groundComms(axLogPath=LOG_PATH, interfaces=i)
    # reader = axreader.axreader(filePath=LOG_PATH, interfaces=AX_INTERFACES, sources=AX_SOURCES, destinations=AX_DESTINATIONS)

    # while False:
    while True:
        # Get packets from axreader

        gc.update()

        # for packet in packets:
        #     print packet
        #     print "--------"

        #     # Parse the commands
        #     gc.parseCommands(packet.data)
Example #13
0
'''
Created on 05/08/2013

@author: Alejandra

'''

import arbol
import interfaces

   

if __name__ == '__main__':
    pass
#    myclass=arbol.arbol()
#    myclass.action()
    
    inter= interfaces.interfaces()
    inter.interaction()
#    inter.all()

Example #14
0
            )
        parser.add_argument(
            'kwargs',
            action='store',
            help='Args: key1=value1,key2=value2...keyn=valuen',
            nargs='?')
    return parser.parse_args(args)

if __name__ == '__main__':
    index = sys.argv.index('rm') if 'rm' in sys.argv else\
        sys.argv.index('list') if 'list' in sys.argv else\
        sys.argv.index('add') if 'add' in sys.argv else len(sys.argv)
    ms = mainparser(sys.argv[1:(index+1)])
    os = secondaryparser(sys.argv[index+1:], ms.command)

    intfile = interfaces(ms.input)

    if ms.command == 'list':
        if ms.verbose:
            print 'List command applied'
        ms.output = "-"
    elif ms.command == 'add':
        if ms.verbose:
            print 'Add command applied'
        kw = dict() if not os.kwargs else\
            dict(i.split('=') for i in os.kwargs.split(','))
        if ms.verbose:
            print 'kwargs parsed: %s' % str(kw)
        if os.type == 'loopback':
            wizards.addloopback(intfile, ms.verbose, **kw)
        if os.type == 'device':
Example #15
0
 def __init__(self,basedir=".",mode="initial",kernel=0):
     self.basedir = basedir
     self.mode = mode
     self.cores = multiprocessing.cpu_count()
     self.wrapper = wrappers.gromacswrapper()
     self.distparser = parser.gdistparser()
     self.filesystem = filesystem.filesystem()
     self.interfaces = interfaces.interfaces()
     self.orderparameters = orderparameters.orderparameters()
     self.helper = helpers.helpers()
     self.kernels = kernels.kernels(kernel)
     self.qsubsystem = qsubsystem.qsubsystem()
     
     #Initialize the logger
     if kernel=="head":
         self.log = gtpslogging.log("info",basedir,kernel)
     elif kernel=="reverse":
         self.log = gtpslogging.log("info",basedir,kernel)   
     else:
         self.log = gtpslogging.log("info",basedir,kernel)
     
     self.log.log.debug("logfile created")
     self.log.log.info(str(self.cores) + " CPUs detected")
     
     self.interfaces.readInterfaces(os.path.join(basedir,"options","interfaces.txt"))
     self.log.log.info("Read Interfaces Forward : " + str(self.interfaces.interfaces[0]))
     self.log.log.info("Read Interfaces Backward : " + str(self.interfaces.interfaces[1]))
     
     self.kernels.readKernelOptions(os.path.join(basedir,"options","kerneloptions.txt"))
     
     #read the stables states from a file
     self.orderparameters.readOP(os.path.join(basedir,"options","orderparameters.txt"))
     self.log.log.info("Read OP : " + str(self.orderparameters.op[0]))
     
     
     """
     This array holds all the information about the paths. Each trajectory consists of a 
     forward-part and a backward-part. The trajectory can either be a forward trajectory
     or a backward trajectory. Forward trajectroies start in A.
     """
     
     self.paths = []
     self.npaths = 0
     for i in range(self.interfaces.ninterfaces[0]):
         self.paths.append(pathdata.pathdata(i,basedir,mode,forward=True,forwardpart=True,interface=self.interfaces.interfaces[0][i]))
         self.paths.append(pathdata.pathdata(i,basedir,mode,forward=True,forwardpart=False,interface=self.interfaces.interfaces[0][i]))
         self.npaths += 1
     for i in range(self.interfaces.ninterfaces[1]):
         n = i + self.interfaces.ninterfaces[0]
         self.paths.append(pathdata.pathdata(n,basedir,mode,forward=False,forwardpart=True,interface=self.interfaces.interfaces[1][i]))
         self.paths.append(pathdata.pathdata(n,basedir,mode,forward=False,forwardpart=False,interface=self.interfaces.interfaces[1][i]))
         self.npaths += 1
     
     self.reversePaths = []
     for rp in self.interfaces.reversepaths[0]:
         self.reversePaths.append(pathdatareverse.pathdatareverse(0, basedir, mode, forward=True, forwardpart=True, interface=rp, state=0))    
     for rp in self.interfaces.reversepaths[1]:
         self.reversePaths.append(pathdatareverse.pathdatareverse(0, basedir, mode, forward=True, forwardpart=True, interface=rp, state=1))
     
     self.kernels.generateKernelLists(self.npaths)
     
     self.interfacedir = int(float(self.paths[0].options.runoptions["interfacecoordinate"]))
     print self.interfacedir