def retrieve_login_code(self, request_date=datetime.now()):
        print("Retrieving login code.")
        try:
            self.outlook.select_folder('INBOX')

            emails_from_joe = self.outlook.search([
                'FROM', '*****@*****.**', 'SUBJECT',
                'FW: Login code'
            ])
            if emails_from_joe:
                raw_message = self.outlook.fetch(
                    [emails_from_joe[-1]], ['BODY[]', 'FLAGS', 'ENVELOPE'])
                for key, value in raw_message.items():
                    timestamp = value[b'ENVELOPE'].date
                    if timestamp < request_date:
                        print(
                            f"Emails from Joe exist. However, latest email is {timestamp.strftime('%m/%d/%Y %H:%M:%S')} which is before {request_date.strftime('%m/%d/%Y %H:%M:%S')}. Waiting 30 seconds."
                        )
                        sleep(30)
                        return self.retrieve_login_code(request_date)
                    body = str(value[b'BODY[]'])
                    codes = re.findall(r"\\n([0-9]+)<", body)

                    return codes[0]
            print("Emails from Joe do not exist. Waiting 60 seconds.")
            sleep(60)
            return self.retrieve_login_code(request_date)
        except:
            if not NetworkManager().is_connected():
                print("Network issue.")
                sleep(90)
                self.retrieve_login_code(request_date)
            else:
                print(f"Unexpected error: {sys.exc_info()[0]}")
Пример #2
0
    def __init__(self):
        self.settings = Settings()
        self.credentials = Credentials()
        self.display = Display()
        self.networkManager = NetworkManager()

        self.previous_hour1 = self.previous_hour2 = -1
        self.previous_minute1 = self.previous_minute2 = -1
        self.previous_second2 = self.previous_count = -1

        self.loop = get_event_loop()

        rst_cause = reset_cause()

        if rst_cause in [PWRON_RESET, SOFT_RESET]:
            self.power_on_reset_wkfl()
        elif rst_cause in [HARD_RESET]:
            self.hard_reset_wkfl()
        elif rst_cause == DEEPSLEEP_RESET:
            self.deepsleep_reset_wkfl()
        else:
            self.other_reset_wkfl()

        self.loop.run_forever()
        self.loop.close()
Пример #3
0
def mpls_remove_fns(desc):

    fns_id= libnetvirt.getUuidFromFNS(desc) 
    print "remove id " + str(fns_id) + "num of endpoints: " + str(libnetvirt.getNepFromFNS(desc))
    
    #libnetvirt.printFNS(desc)
    
    D = Database ('libnetvirt.sqlite')
    for i in range(0,libnetvirt.getNepFromFNS(desc)):

        ep = libnetvirt.getEndpoint(desc,i)
        r_id = libnetvirt.getSwIdFromEp(ep)
        
        # Get router name
        #r_name = str(libnetvirt.getSwIdFromEp(ep))
        r_name = D.getRouterName(r_id)
        # Get the router user name
        r_uname = D.getRouterUserName(r_id)             
        vlan =  libnetvirt.getVlanFromEp(ep)
        pe_if = libnetvirt.getPortFromEp
        vrf = 'vrf' +  str(fns_id)
        
        #Calling the scripts for configuration. Uncomment when the network is available
        NM = NetworkManager(r_name, r_uname)
        if NM != None:
            NM.stop_configuration(vlan, vrf,pe_if)
            NM.close_ssh()
        else:
            print "Error in applying configuration"
        


    return 0
Пример #4
0
def main():
    network = NetworkManager()
    json_string = network.getPresence()
    seats = json.loads(json_string)

    db_manager = DBManager()
    for item in seats:
        db_manager.create_seat(item)
Пример #5
0
 def __init__(self):
     self.network_manager = NetworkManager(self.state_changer)
     self.running = True
     self.labels, self.entries, self.buttons = dict(), dict(), dict()
     self.root = Tk()
     self.override_data = BooleanVar()
     self.override_data.set(True)
     self.tk_root_setup()
Пример #6
0
def mpls_create_fns(desc):
    print "create fns"
    #libnetvirt.printFNS(desc)
    fns_id= libnetvirt.getUuidFromFNS(desc)
    D = Database ('libnetvirt.sqlite')
    for i in range(0,libnetvirt.getNepFromFNS(desc)):

        ep = libnetvirt.getEndpoint(desc,i)
        r_id = libnetvirt.getSwIdFromEp(ep)

        # Get router name
        #r_name = str(libnetvirt.getSwIdFromEp(ep))
        r_name = D.getRouterName(r_id)

        # Get the router user name
        r_uname = D.getRouterUserName(r_id)

        # Get the router interface
        r_interface = D.getRouterInterface(r_id)+str(libnetvirt.getPortFromEp(ep))

        #r_uname = "root"
        #r_interface = "eth3"
        r_d_net = '192.66.23.0'
        
        pe_address = libnetvirt.getAddressFromEp(ep)
        #ce_address = libnetvirt.getAddressCEFromEp(ep)
        
        #we need net address for CE
        tmp = commands.getoutput('ipcalc -n ' + str(pe_address))
        tmp = tmp.split()
        ce_net = tmp[16]
        
        vlan =  libnetvirt.getVlanFromEp(ep)
        vrf = 'vrf' +  str(fns_id)
        
        #get address from global configuration database
        r_d =  r_d_net + ':' + str(fns_id)
        
        #call script for PE configuration
        #Calling the scripts for configuration. Uncomment when the network is available
        NM = NetworkManager(r_name, r_uname)
        if NM != None:
            NM.start_configuration(r_interface, pe_address, ce_net, r_d, vlan, vrf)
            NM.close_ssh()
        else:
            print "Error in applying configuration"


    return 0
Пример #7
0
 def SendCommandMessage(target):
     commandMessage = MessageFactory.createCommandMessage(
         target, 'hello world')
     NetworkManager().outgoingMessages.put(commandMessage)
Пример #8
0
import NetworkConstants

if __name__ == '__main__':
    global MY_NAME
    MY_NAME = 'CHRONOS'

    def SendCommandMessage(target):
        commandMessage = MessageFactory.createCommandMessage(
            target, 'hello world')
        NetworkManager().outgoingMessages.put(commandMessage)

    initialise()  # Initialise the network API
    sleep(1)
    InsTable().printTable()

    otherIsaacs = NetworkManager().getConnectedDevices()
    if (len(otherIsaacs) > 0):
        target = otherIsaacs[0]

        pingDevice(target)
        sendCommand(target, 'KILL SELF')

    sleep(5)

    running = True

    while running:

        userInput = input('Enter command (type QUIT or EXIT to terminate):\n')
        userInput = userInput.upper()
Пример #9
0
from NetworkManager import NetworkManager
from time import sleep

if __name__ == '__main__':
    nm = NetworkManager(NetworkManager.MODE_CLIENT_SERVER,
                        NetworkManager.ROLL_CLIENT, '127.0.0.1', 50007)
    nm.client_open()
    nm.transmit_data(NetworkManager.DST_SERVER, "HELLO WORLD")

    while True:
        sleep(1)
Пример #10
0
def menu():
    options = {1:"network inventory info.",2:" all devices info.",3:"device info.",4:"device description.(!!!!)"}
    print "------------------------------"
    print "MENU"
    print "------------------------------"
    for key in options.keys():
        print  str(key) + ")Print " + options[key]
    choise = raw_input("Enter: ")

    return int(choise)

if __name__ == "__main__":
    #print "Starting network manager..."
    try:
        print "Starting network manager..."
        nm = NetworkManager('192.168.111.138')
        print "Network manager started."
        
        while(1):
            option = menu()
            if option == 1:
                nm.printInventory()
            elif option == 2:
                nm.printDeviceInfo()
            elif option == 3:
                info_type = raw_input("Enter information type: ")
                device_id = raw_input("Enter device_id: ")
                nm.printDataForDevice(info_type.rstrip(),device_id.rstrip())
            else:
                exit()
    except Exception,exception:
Пример #11
0
class SimulationCreator:
    __simulation = Simulation()
    __networkManager = NetworkManager()
    __sensorsManager = SensorsManager(__networkManager)
    __tripManager = TripManager(__networkManager)

    def __init__(self):
        SimulationCreator.__simulation = Simulation()
        SimulationCreator.__networkManager = NetworkManager()
        SimulationCreator.__sensorsManager = SensorsManager(SimulationCreator.__networkManager)
        SimulationCreator.__tripManager = TripManager(SimulationCreator.__networkManager)

    # -------------------------------- Net file creation ------------------------------------------------
    def set_map_box(self, mapBox):
        SimulationCreator.__simulation.set_map_box(mapBox)

    def get_map_box(self):
        return SimulationCreator.__simulation.get_map_box()

    #Call NetworkManager to create map.net.xml
    def create_network_file(self):
        project_directory = SimulationCreator.__networkManager.create_project_directory()
        network_file_path = SimulationCreator.__networkManager.get_network_file(
            SimulationCreator.__simulation.get_map_box()
        )
        SimulationCreator.__simulation.set_project_directory_path(project_directory)
        SimulationCreator.__simulation.set_network_file(network_file_path)

    # Generate a new network file including splitted edges
    def split_network_edges(self):
        SimulationCreator.__networkManager.generate_network_file_with_splitted_edges(
            SimulationCreator.__simulation.get_flows(),
            SimulationCreator.__simulation.get_sensors_distance()
        )
    # ---------------------------------------------------------------------------------------------------

    # -------------------------------- Flows definition -------------------------------------------------
    def define_traffic_flows(self, inFlowPoints, outFlowPoints):
        self.flows_file_path, self.flows = SimulationCreator.__tripManager.generate_flows_file(inFlowPoints, outFlowPoints)
        SimulationCreator.__simulation.set_flows(self.flows)

    def create_route_file(self):
        self.route_file = SimulationCreator.__tripManager.generate_route_file(self.flows_file_path)
        SimulationCreator.__tripManager.set_vehicle_types_in_route_file(self.route_file)
        SimulationCreator.__simulation.set_route_file(self.route_file)
        SimulationCreator.__simulation.add_vehicle_types(self.get_vehicle_types())

    # ---------------------------------------------------------------------------------------------------

    # ---------------------------------- Incident lanes definition --------------------------------------
    def add_incidents(self, incidents):
        #Calculate each incident edge_id before setting them in simulation instance
        incident_updated_lanes = SimulationCreator.__tripManager.set_incident_lanes(incidents)
        SimulationCreator.__simulation.add_incidents(incident_updated_lanes)
        Sink.incidents = incident_updated_lanes
    # ---------------------------------------------------------------------------------------------------

    # ---------------------------------- Vehicle types defintion ----------------------------------------
    def add_vehicle_type(self, vehicle_type):
        SimulationCreator.__tripManager.add_vehicle_type(vehicle_type)
        SimulationCreator.__simulation.add_vehicle_types([vehicle_type])

    def set_vehicle_types_percentages(self, vehicle_types_percentages):
        SimulationCreator.__tripManager.set_vehicle_types_percentages(vehicle_types_percentages)

    def get_vehicle_types(self):
        return SimulationCreator.__tripManager.get_vehicle_types()
    # ---------------------------------------------------------------------------------------------------

    # ------------------------------------- Add sensors -------------------------------------------------
    def set_sensors_distance(self, distance):
        SimulationCreator.__simulation.set_sensors_distance(distance)

    def create_sensors(self):
        LaneChange.EdgeLength = SimulationCreator.__simulation.get_sensors_distance()

        self.sinks, self.sensors, self.sensors_file = SimulationCreator.__sensorsManager.create_sensors(
            SimulationCreator.__simulation.get_flows(),
            SimulationCreator.__simulation.get_incidents()
        )
        SimulationCreator.__simulation.add_sensors(self.sensors)
        SimulationCreator.__simulation.add_sinks(self.sinks)
        SimulationCreator.__simulation.set_sensors_file(self.sensors_file)
    # ---------------------------------------------------------------------------------------------------

    # ------------------------------------- Simulation Creation -----------------------------------------
    def set_sim_duration(self, duration):
        SimulationCreator.__simulation.set_duration(duration)

    #Create Simulation Config file 'map.sumocfg'
    def createSimulation(self):
        SimulationCreator.__simulation.create_sumo_config_file()
        return SimulationCreator.__simulation
Пример #12
0
 def __init__(self):
     SimulationCreator.__simulation = Simulation()
     SimulationCreator.__networkManager = NetworkManager()
     SimulationCreator.__sensorsManager = SensorsManager(SimulationCreator.__networkManager)
     SimulationCreator.__tripManager = TripManager(SimulationCreator.__networkManager)
Пример #13
0
    def train(self):
        if not os.path.exists('weights/'):
            os.makedirs('weights/')

        previous_acc = 0.0
        total_reward = 0.0

        policy_sess = tf.Session()
        K.set_session(policy_sess)

        with policy_sess.as_default():
            # create the Controller and build the internal policy network
            controller = Controller(policy_sess, self.num_conv_layers, self.state_space,
                                    reg_param=self.regularization,
                                    exploration=self.exploration,
                                    controller_cells=self.num_control_cells,
                                    embedding_dim=self.embedding_dim,
                                    restore_controller=self.restore_model)

        # create the Network Manager
        manager = NetworkManager(self. dataset, epochs=self.num_epochs, child_batchsize=self.batch_size,
                                 clip_rewards=self.clip_rewards, acc_beta=self.accuracy_beta)

        # create the Model Constructor
        constructor = ModelConstructor(self.input_size, self.output_size, self.num_conv_layers,
                                       self.num_dense_layers, self.dense_config)

        # get an initial random state space if controller needs to predict an
        # action from the initial state
        state = self.state_space.init_random_states(self.num_conv_layers)
        print state
        print("Initial Random State : ", self.state_space.parse_state_space_list(state))
        print()

        # clear the previous files
        controller.remove_files()

        # train for number of trails
        for trial in range(self.num_trials):
            with policy_sess.as_default():
                K.set_session(policy_sess)
                actions = controller.get_action(state)  # get an action for the previous state

            # print the action probabilities
            self.state_space.print_actions(actions)
            print("Predicted actions: ", self.state_space.parse_state_space_list(actions, local=True))

            # build a model, train and get reward and accuracy from the network manager
            reward, previous_acc = manager.get_rewards(constructor, self.state_space.parse_state_space_list(actions, local=True))
            print("Rewards: ", reward, "Accuracy: ", previous_acc)

            with policy_sess.as_default():
                K.set_session(policy_sess)

                total_reward += reward
                print("Total reward: ", total_reward)

                # actions and states are equivalent, save the state and reward
                first_state = state[0]
                state = actions
                controller.store_rollout(state, reward)

                # train the controller on the saved state and the discounted rewards
                loss = controller.train_step(first_state)
                print("Trial %d: Controller loss: %0.6f" % (trial + 1, loss))

            print()

        print("Total Reward: ", total_reward)
 def __init__(self, passed_config):
     self.state = SYNC_STATE.STOP
     self.config = passed_config
     self.network = NetworkManager(passed_config)
Пример #15
0
 def __init__(self):
     self.clients = {}
     self.network_manager = NetworkManager(self.clients)
     print("Init done, server started")