コード例 #1
0
ファイル: stadyna.py プロジェクト: tempbottle/StaDynA
def getDeviceForDynAnalysis():
    dev_list = Device.get_devices_list()
    
    devNum = len(dev_list)
    
    if devNum <= 0:
        logger.error("No device has been detected! Connect your device and restart the application!")
        return None
    
    if devNum == 1:
        return Device.get_device(dev_list[0])
    
    choice = None
    if devNum > 1:
        print "Select the device to use for analysis:\n"
        for i in xrange(0, devNum):
            print "%d. %s\n" % ((i + 1), dev_list[i])
        
        while not choice:
            try:
                choice = int(raw_input())
                if choice not in range(1, devNum+1):
                    choice = None
                    print 'Invalid choice! Choose right number!'
            except ValueError:
                print 'Invalid Number! Choose right number!'
        
        
    return Device.get_device(dev_list[choice - 1])
コード例 #2
0
ファイル: test-update_system.py プロジェクト: erikb85/HidaV
def init( ):
    """ Initialise the device handle, boot to NAND flash.
        @returns: a device handle, i.e. a class Device instance.
    """

    print "  Initialising the device."
    print "  (Device will be powercycled in 60 secs if unresponsive)"
    power.power(1)
    t = threading.Timer( 60, powercycle )
    t.start()
    dev = Device( devtype = "hidav" )
    wait_networking( dev )    
    t.cancel()

    # set currently used partitions to the first partitions, 
    # so upgrade (detecting this) will use the other partitions
    dev.bootconfig = { "kernel" : 2, "rootfs" : 4 } 

    print "  Firmware version: %s" % dev.firmware_version
    print "  Boot config (current):"
    print "     Kernel:      /dev/mtd%s" % dev.bootconfig["kernel"]
    print "     rootfs: /dev/romblock%s" % dev.bootconfig["rootfs"]
    print "     epoch :             #%s" % dev.bootconfig["epoch"]

    print "  Booting into NAND..."
    dev.reboot( to_nand = True )
    wait_networking( dev )    
    return dev
コード例 #3
0
ファイル: MultiAutoShark.py プロジェクト: knolls/cisco_class
def crawlDevice(ip_address,user,pw):
	sw1 = Device(ip=ip_address, username=user, password=pw)
	sw1.open()

	# Getting everything into dicts
	sh_vrf = get_vrf(sw1)
	int_brief = get_ip_int_b(sw1)
	int_status = get_int_status(sw1)
	hostname,proccesor_ID,version = get_hostname_serial_version(sw1)
	neighbors = get_cdp_info(sw1)
	port_channels = get_portchannel_sum(sw1)
	# Adding all data into objs
	LocalDevice = root_Device(hostname,proccesor_ID,version,ip_address,user,pw)

	for singleVrf in sh_vrf:
		vrf = Vrf(singleVrf["vrf-name-out"])
		if "TABLE_prefix" in singleVrf["TABLE_addrf"][ "ROW_addrf"].keys():
			for prefixes in singleVrf["TABLE_addrf"][ "ROW_addrf"]["TABLE_prefix"]["ROW_prefix"]:
				vrf.addPrefix(prefixes["ipprefix"])
			LocalDevice.addVrf(vrf)

	for ipInter in int_brief:
		LocalDevice.addIp(ipInter["ROW_intf"]["prefix"])

	LocalDevice.addPortChannel(port_channels)
	for interface in int_status:
		LocalDevice.addIp(interface)

	for neighbor in neighbors:
		neighEntry = Neighbors(root_Device,neighbor)
		LocalDevice.addNeighbor(neighEntry)



	return LocalDevice
コード例 #4
0
def main():
    '''

    Main loop to retrieve data

    :return:
    '''
    args = getargs()

    username = args.user

    if not username:
        username = raw_input("Device Username:")

    password = getpass.getpass('Device password:')

    switch = Device(ip=args.switch, username=username, password=password)

    switch.open()

    result = get_forwardingpath(switch,
                                interface=args.interface,
                                src=args.source,
                                dst=args.destination,
                                lbalgo='ip' )

    print 'Traffic flowing from %s to %s will use physical interface %s' % (args.source, args.destination, result)
コード例 #5
0
def active_device(mac, ip='0.0.0.0', name='', time_stamp = datetime.datetime.now()):
    device_list = load_db()

    #time_stamp = datetime.datetime.now()

    mac_list = []
    for d in device_list:
        mac_list.append(d._mac)

    if not mac in mac_list:
        #have not found this device previously
        if len(name) < 1:
            #FIXME: should be more automated - no input should really be required
            name = input('What is the name of this machine? ('+ip+', '+mac+') ')

        from device import Device

        unkn_d = Device(name, mac)

        unkn_d.add_ip(ip)
        unkn_d.add_ts(time_stamp)

        #print("Adding new DEVICE to DB")
        device_list.append(unkn_d)

    else:
        # already part of the db - only add time stamp
        #print("Updating existing DEVICE in DB")

        index = mac_list.index(mac)
        device_list[index].add_ip(ip)
        device_list[index].add_ts(time_stamp)

    save_db(device_list)
コード例 #6
0
ファイル: cube.py プロジェクト: MathewSam/phosphene
 def __init__(self, port, dimension=10, emulator=False):
     Device.__init__(self, "Cube", port)
     self.array = numpy.array([[\
             [0]*dimension]*dimension]*dimension, dtype='bool')
     self.dimension = dimension
     self.emulator = emulator
     self.name = "Cube"
コード例 #7
0
    def __init__(self, name):
        Device.__init__(self, name)
        self.ControlPanelClass = AudioTestGenControlPanel

        self.freqs = ObservableVariable([1000, 1000])
        self.freqs.changed.connect(self.change_freqs)

        caps = Gst.caps_from_string(self.SINGLE_CHANNEL_AUDIO_CAPS)

        self.src0 = Gst.ElementFactory.make('audiotestsrc', None)
        self.bin.add(self.src0)
        self.src0.set_property('is-live', True)

        self.src1 = Gst.ElementFactory.make('audiotestsrc', None)
        self.bin.add(self.src1)
        self.src1.set_property('is-live', True)

        self.interleave = Gst.ElementFactory.make('interleave', None)
        self.bin.add(self.interleave)

        self.src0.link_filtered(self.interleave, caps)
        self.src1.link_filtered(self.interleave, caps)

        self.add_output_audio_port_on(self.interleave, "src")

        self.change_freqs(self.freqs.get_value())
コード例 #8
0
ファイル: int_brief.py プロジェクト: lisroach/9k_scripts
def main():
	'''Call the show_ip_int_brief function and read in from file'''
	
	#check they entered a filename
	if len(sys.argv) <= 1:
		print "You must enter a filename: int_brief.py <filename>"
		sys.exit()
	
	else:
		#check if the file name is correct and can be opened
		try:
			script, filename = sys.argv
			with open(filename, 'r') as fp:	#with will close file
				for line in fp:				#loop through the lines
					switch_admin = []
					if len(line.split()) == 3:	#check if there are three variables per line

						for word in line.split():	#loop through the words and add them to a list
							#fill a list with the items in the line - should be three
							switch_admin.append(word)
						
						#create the switch object
						switch = Device(ip=switch_admin[0], username=switch_admin[1], password=switch_admin[2])
						switch.open()
						#call the  function
						show_ip_int_brief(switch, switch_admin[0])
					else:
						print "Your file variables are incorrect. It should be <ip address> <username> <password> per line."
						sys.exit()
		except IOError:
			print "Your file was mistyped! Please try again."
			sys.exit()
コード例 #9
0
ファイル: glutdevice.py プロジェクト: Ripsnorta/pyui2
    def __init__(self, width, height, fullscreen):
        print "glut::__init__()"
        Device.__init__(self)

        self.size = (width, height)
        self.fullscreen = fullscreen

        glutInit(sys.argv)
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)

        if self.fullscreen:
            glutGameModeString("%dx%d:[email protected]" % self.size )
            self.windowID = glutEnterGameMode()
        else:
            glutInitWindowSize(self.size[0], self.size[1])
            glutInitWindowPosition(0,0)
            self.windowID = glutCreateWindow("")

        glutSetWindow(self.windowID)

        glutReshapeFunc(self.reSizeGLScene)
        glutMouseFunc(self.onMouse)
        glutMotionFunc(self.onMotion)
        glutPassiveMotionFunc(self.onMotion)
        glutKeyboardFunc(self.onKeyDown)
        glutKeyboardUpFunc(self.onKeyUp)
        glutSpecialFunc(self.onSpecialDown)
        glutSpecialUpFunc(self.onSpecialUp)

        self.graphicsDevice = OpenGLGraphics(self.size)
コード例 #10
0
ファイル: device_observed.py プロジェクト: hazelor/COO_new
 def observed_devices(self, user_id):
     dev_ids = self.find_by('where user_id = ?', user_id)
     devices = []
     dev = Device()
     for dev_id in dev_ids:
         devices.append(dev.get(dev_id.device_id))
     return devices
コード例 #11
0
ファイル: dsk.py プロジェクト: efirmaster/open-playout
    def __init__(self, name):
        Device.__init__(self, name)
        self.ControlPanelClass = DskControlPanel

        self.file = ObservableVariable()
        self.file.changed.connect(self.file_changed)

        self.alpha = ObservableVariable(0)
        self.alpha.changed.connect(self.alpha_changed)

        # While input convert doesn't seem explicitly necessary, it seems to
        # give better performance.  Not sure why.
        self.inputconvert = self.add_element('videoconvert')
        self.mixer = self.add_element('videomixer')
        self.outputconvert = self.add_element('videoconvert')

        self.add_input_video_port_on(self.inputconvert)
        self.inputconvert.link(self.mixer)

        self.mixer.link(self.outputconvert)
        self.add_output_video_port_on(self.outputconvert)

        self.mixer.get_static_pad('sink_0').set_property('zorder', 0)

        self.alpha.set_value(1.0)
コード例 #12
0
ファイル: usb4butia.py プロジェクト: nfurquez/LabRobEmb2013
 def callModule(self, modulename, board_number, number, function, params = []):
     """
     Call one function: function for module: modulename in board: board_name
     with handler: number (only if the module is pnp, else, the parameter is
     None) with parameteres: params
     """
     try:
         board = self._bb[board_number]
         if board.devices.has_key(number) and (board.devices[number].name == modulename):
             return board.devices[number].call_function(function, params)
         else:
             if modulename in self._openables:
                 if modulename in board.get_openables_loaded():
                     number = board.get_device_handler(modulename)
                 else:
                     board.add_openable_loaded(modulename)
                     dev = Device(board, modulename)
                     number = dev.module_open()
                     dev.add_functions(self._drivers_loaded[modulename])
                     board.add_device(number, dev)
                 return board.devices[number].call_function(function, params)
             else:
                 if self._debug:
                     print 'no open and no openable'
                 return ERROR
     except Exception, err:
         if self._debug:
             print 'error call module', err
         return ERROR
コード例 #13
0
 def __init__(self, name, major=None, minor=None, exists=None,
              format=None, parents=None, sysfsPath='', vendor="",
              model=""):
     Device.__init__(self, name, format=format,
                     major=major, minor=minor, exists=True,
                     parents=parents, sysfsPath=sysfsPath,
                     vendor=vendor, model=model)
コード例 #14
0
ファイル: pygamedevice.py プロジェクト: Ripsnorta/pyui2
    def __init__(self, width, height, fullscreen, mode=P2D):
        Device.__init__(self)

        self.mode = mode
        self.size = (width, height)

        pygame.init()
        pygame.key.set_mods(KMOD_NONE)
        pygame.mouse.set_visible(0)

        if mode == PygameDevice.P2D:
            flags = 0
            if fullscreen:
                flags = flags | pygame.locals.FULLSCREEN | pygame.locals.SWSURFACE

            self.graphicsDevice = PygameGraphics(self.size, flags)

        elif mode == PygameDevice.OGL:
            from openglgraphics import OpenGLGraphics
            
            flags = pygame.locals.OPENGL | pygame.locals.DOUBLEBUF
            if fullscreen:
                flags = flags | pygame.locals.FULLSCREEN

            self.graphicsDevice = OpenGLGraphics(self.size, flags, pygame.display.set_mode(self.size, flags))

        else:
            raise device.DeviceException("Invalid Graphics Mode Specified")
コード例 #15
0
ファイル: device_test.py プロジェクト: rtshadow/miscs
class DeviceTest(unittest.TestCase):
    def setUp(self):
        self.block_size = 1
        self.blocks = 100
        self.dev = Device("data", self.block_size, self.blocks)
        self.data = [randrange(0, 256) for i in range(0, self.blocks)]
        for i, block in enumerate(self.data):
            self.dev.write_block(i, chr(block))

    def test_memory_read(self):
        self.should_preserve_data(self.dev)

    def test_file_read(self):
        self.dev.close()
        dev = Device("data", self.block_size, self.blocks)
        self.should_preserve_data(dev)

    def should_preserve_data(self, dev):
        for i, block in enumerate(self.data):
            read = dev.read_block(i)
            self.assertEqual(read, chr(block))

    @unittest.expectedFailure
    def test_fail_to_write_data_bigger_than_block(self):
        self.dev.write_block(0, b'aa')

    @unittest.expectedFailure
    def test_fail_with_out_of_bounds(self):
        self.dev.write_block(self.blocks + 1, b'a')

    def tearDown(self):
        self.dev.close()
コード例 #16
0
ファイル: disk.py プロジェクト: MusaSakizci/yali-family
    def __init__(self, device, format=None, parents=None,
                 exists=True, size=None, major=None, minor=None,
                 sysfsPath='', serial=None, model="", vendor="", bus=""):
        """ Create a Disk instance.

            Arguments:

                device -- the device name (generally a device node's basename)

            Keyword Arguments:

                size -- the device's size (units/format TBD)
                major -- the device major
                minor -- the device minor
                sysfsPath -- sysfs device path
                format -- a DeviceFormat instance
                parents -- a list of required Device instances
                removable -- whether or not this is a removable device

            Disk always exist.
        """
        Device.__init__(self, device, format=format, size=size,
                        major=major, minor=minor, exists=exists,
                        model=model, serial=serial, vendor=vendor,bus=bus,
                        sysfsPath=sysfsPath, parents=parents)
コード例 #17
0
ファイル: position.py プロジェクト: hazelor/COO_new
 def validate(self):
     dev = Device()
     if not dev.creator(self.device_id):
         return False
     if self.duration <=0:
         return False
     return True
コード例 #18
0
def main():

    switch = Device(ip='172.31.217.136', username='admin', password='cisco123')
    switch.open()

    show_boot_config = copy_bootflash(switch)
    print show_boot_config
コード例 #19
0
ファイル: update_descrip.py プロジェクト: mijo77/cisco_class
def main():

    switch = Device(ip='172.31.217.133',username='admin',password='cisco123')
    switch.open()

    mac_table = get_mac(switch)
    arp_table = get_arp(switch)

    print "Will parse the following MAC and ARP tables obtained from the switch:"
    print json.dumps(mac_table, indent=4)   
    print json.dumps(arp_table, indent=4)
    
    # Loop through the MAC address table
    for mac_entry in mac_table:
        # If the MAC address is present in the ARP table
        if mac_entry in arp_table:

            #Attempt name resolution.  gethostbyaddr will throw an exception if host is not found
            try:
                
                ip_address = arp_table[mac_entry]
                interface_name = mac_table[mac_entry]
                
                hostname = gethostbyaddr(ip_address)
                
                print hostname[0] + " (" + ip_address + ") is on " + interface_name
                
                # Pass the result to write_descript to apply the hostname to the NX-OS interface
                write_descript(switch,interface_name,hostname[0])
                
            except:
                # For simplicity, we will assume that any exception is a host not found and move on
                print "No hostname for " + ip_address + " was found... skipping"
コード例 #20
0
ファイル: partitionISO.py プロジェクト: TiejunChina/photon
    def __init__(self, maxy, maxx, install_config):
        self.maxx = maxx
        self.maxy = maxy
        self.win_width = maxx - 4
        self.win_height = maxy - 4
        self.install_config = install_config
        self.path_checker = []

        self.win_starty = (self.maxy - self.win_height) // 2
        self.win_startx = (self.maxx - self.win_width) // 2

        self.text_starty = self.win_starty + 4
        self.text_height = self.win_height - 6
        self.text_width = self.win_width - 6
        self.install_config['partitionsnumber'] = 0
        self.devices = Device.refresh_devices_bytes()
        self.has_slash = False
        self.has_remain = False
        self.has_empty = False

        self.disk_size = []
        for index, device in enumerate(self.devices):
            self.disk_size.append((device.path, int(device.size) / 1048576))

        self.window = Window(self.win_height, self.win_width, self.maxy, self.maxx,
                             'Welcome to the Photon installer', False, can_go_next=False)
        Device.refresh_devices()
コード例 #21
0
ファイル: host.py プロジェクト: AGFeldman/jaka
    def __init__(self, id_):
        Device.__init__(self, id_)
        self.endpoint_for_router = None

        self.bits_sent_graph_tag = globals_.stats_manager.new_graph(
                title='Total Bits Sent by %s' % self.id_,
                ylabel='Total Bits'
        )
        self.bit_rate_sent_graph_tag = globals_.stats_manager.new_graph(
                title='Rate of Data Sent by %s' % self.id_,
                ylabel='Rate (bits/sec)',
                is_rate=True
        )
        self.bits_received_graph_tag = globals_.stats_manager.new_graph(
                title='Total Bits Received by %s' % self.id_,
                ylabel='Total Bits'
        )
        self.bit_rate_received_graph_tag = globals_.stats_manager.new_graph(
                title='Rate of Data Received by %s' % self.id_,
                ylabel='Rate (bits/sec)',
                is_rate=True
        )

        self.bits_sent = 0
        self.bits_received = 0
コード例 #22
0
    def __init__(self, name, pattern=0):
        Device.__init__(self, name)
        self.ControlPanelClass = VideoTestGenControlPanel

        self.pattern = ObservableVariable(pattern)
        self.pattern.changed.connect(self.change_pattern)

        self.src = Gst.ElementFactory.make('videotestsrc', None)
        self.bin.add(self.src)
        self.src.set_property('pattern', self.pattern.get_value())

        self.convert = Gst.ElementFactory.make('videoconvert', None)
        self.bin.add(self.convert)

        self.text_overlay = Gst.ElementFactory.make('textoverlay', None)
        self.bin.add(self.text_overlay)
        self.text_overlay.set_property("text", self.name)
        self.text_overlay.set_property("shaded-background", True)

        self.caps_filter = Gst.ElementFactory.make('capsfilter', None)
        self.bin.add(self.caps_filter)

        caps = Gst.caps_from_string(Device.DEFAULT_VIDEO_CAPS)
        self.caps_filter.set_property('caps', caps)

        self.src.link(self.text_overlay)
        self.text_overlay.link(self.convert)
        self.convert.link(self.caps_filter)

        self.add_output_video_port_on(self.caps_filter, "src")
コード例 #23
0
ファイル: person.test.py プロジェクト: csuvbakka/myhouse
    def testDeviceStatusUpdate(self):
        d = Device('a', 'abcdefgh', True, OFFLINE)
        p = Person('A', [d])

        self.assertFalse(p.is_home())

        d.status = ONLINE
        self.assertTrue(p.is_home())
コード例 #24
0
ファイル: host.py プロジェクト: ialexryan/CS143-Project
 def __init__(self, identifier):
     Device.__init__(self, identifier)
     self.link = None
     self.flows = {}
     self.clock = None
     self.event_scheduler = None
     self.logger = None
     self.payload_packet_trackers = {}
コード例 #25
0
ファイル: portmap.py プロジェクト: jeremyguthrie/cisco_class
def getneighbors(ip,username,password):
    devices = [ ip ]
    devicecount=0
    while devicecount != len(devices):
        dev = Device(ip=devices[devicecount], username=username, password=password)
        dev.open()
        devices = devices + show_cdwneighbors(dev,devices)
        devicecount+=1
    return devices
コード例 #26
0
ファイル: xml-parser.py プロジェクト: ebuendia/ProyectoPython
def main():
	file = open("test.xml","r")
	line = file.readline()

	while not startDevices(line):
		line = file.readline()

	line = file.readline().strip()
	
	devices = []
	device = ""
	group = ""
	capability = ""
	
	while not endDevices(line):
		if beginDevice(line):
			line = deleteTags(line,"<device ",">")
			att_id = getAttrId(line)
			att_user = getAttrUser(line)
			att_fall = getAttrFall(line)
			
			device = Device(att_id, att_user, att_fall)
			line = file.readline()

		if endDevice(line):
			devices.append(device)
			line = file.readline()

		if beginGroup(line):
			line = deleteTags(line,"<group ",">")
			att_id = getAttrId(line)

			group = Group(att_id)
			group.setDevice(device)
			line = file.readline()

		if endGroup(line):
			device.addGroup(group)
			line = file.readline()

		if beginCapability(line):
			line = deleteTags(line, "<capability ", "/>")
			att_name = getAttrName(line)
			att_value = getAttrValue(line)

			capability = Capability(att_name, att_value)
			capability.setGroup(group)
			group.addCapability(capability)
			line = file.readline()

	print "Devices\n"
	printDevices(devices)
	print "End Devices\n"
	
	file.close()
	return 0
コード例 #27
0
ファイル: rainman_v6.py プロジェクト: rcraner/cisco_class
def connect_pulldata(ipaddr, uname, pword):

  switch = Device(ip=ipaddr, username=uname, password=pword)
  switch.open()

  vtp_facts = ipaddr + ',' + vtp_info(switch)

  csvwriter = csv.writer(open("vtp.csv", "a"))

  csvwriter.writerow([vtp_facts])
コード例 #28
0
    def setup(self, intf=None, orig=False):
        Device.setup(self, orig=orig)
        if self.format and self.format.exists and not self.format.status:
            self.format.device = self.path

        for parent in self.parents:
            if orig:
                parent.originalFormat.setup()
            else:
                parent.format.setup()
コード例 #29
0
def main():

    switch = Device(ip='172.31.217.134', username='admin', password='cisco123')
    switch.open()

    ver = show_dev_version(switch)

    print json.dumps(ver, indent=4)

    ver_check = check_version(switch)
コード例 #30
0
ファイル: devices.py プロジェクト: JulienPalard/mix-machine
 def read(self, limits):
     """Read minimum from one line and <block_size> chars"""
     Device.read(self, limits)
     line = self._readLine()
     if len(line) < self.block_size:
         line += " " * (self.block_size - len(line))
     else:
         line = line[:self.block_size]
     bytes = map(Device._ord, line)
     return bytes