def __init__(self, name, long_desc, short_desc, prior_visit, connections, items, features, load): self.name = name self.long_desc = long_desc self.short_desc = short_desc self.prior_visit = bool(prior_visit == "true") self.connections = connections self.inventory = Inventory(None) self.feature_list = [] directory = "./GameData/Items" for item in items: if item is not None and not load: item_name = self.parser.convert_spaces(item.lower()) item_path = directory + "/{}.json".format(item_name) cur_item = Item.create_item_from_file(item_path) self.inventory.add_item(cur_item) elif item is not None and load: self.inventory = Inventory(items) for obj in features: if obj: cur = Feature(obj["name"], obj["desc"], obj["is_interactive"], obj["interactions"]) self.feature_list.append(cur)
def __init__(self, host, ip, mask, device): self.device = device self.initIA() self.HOST = host self.ip = ip self.mask = mask self.inventory = Inventory(self.HOST) self.status = Status(self.HOST)
def __init__(self, items): self.name = "Boy" self.inventory = Inventory(None) if items is not None: for data in items: if data is not None: cur_item = Item(data["name"], data["description"], data["obtainable"]) self.inventory.add_item(cur_item)
class Player: """Represents the user character in the game Attributes ---------- name : str name of character, defaults to "Boy", not changeable inventory: Inventory contains item objects in player's possession Methods ------- __init__(items) default constructor creates instances using parameters convert_player_to_json() returns object containing player data to write to JSON player_add_item(item) adds item instance to player inventory player_drop_item(item) removes item instance if found in player inventory """ parser = TextParser() def __init__(self, items): self.name = "Boy" self.inventory = Inventory(None) if items is not None: for data in items: if data is not None: cur_item = Item(data["name"], data["description"], data["obtainable"]) self.inventory.add_item(cur_item) def convert_player_to_json(self): player_inventory = self.inventory.convert_inventory_to_json() player_data = {"name": self.name, "inventory": player_inventory} return player_data def player_add_item(self, item): self.inventory.add_item(item) print("\n{} grabbed the {} and placed it in his inventory.".format( self.name, item.name)) def player_drop_item(self, item, room_inventory): for obj in self.inventory.get_inventory_list(): if obj.name.lower() == item: room_inventory.add_item(obj) self.inventory.remove_item(obj) print("{} dropped the {}.".format(self.name, obj.name))
class Room: """Represents a room in the game Attributes ---------- name : str name of room long_desc : str long description displayed on first visit short_desc : str short description displayed upon repeat visit prior_visit : boolean status if room has been visited before connections : list(str) list of names of adjacent rooms inventory : Inventory contains item objects in room feature_list : list(Feature) list of features in room parser : TextParser used to parse item name inputs Methods ------- __init__(name, long_desc, short_desc, prior_visit, connections, items, features, load) default constructor creates instances using parameters from_file_name(file_name) method calls constructor using parameters from JSON file convert_room_to_json returns list of strings representing room attributes get_connection(num) returns name of adjacent room at index get_feature() returns list of features in room examine(feature) searches for feature in room and displays description get_desc() print descriptions based on status of prior_visit get_long_desc() print long_desc get_short_desc() print short_desc room_add_item(item) add item to room inventory room_drop_item(item) drop item from room inventory toggle_visit() toggle prior_visit from False to True """ parser = TextParser() def __init__(self, name, long_desc, short_desc, prior_visit, connections, items, features, load): self.name = name self.long_desc = long_desc self.short_desc = short_desc self.prior_visit = bool(prior_visit == "true") self.connections = connections self.inventory = Inventory(None) self.feature_list = [] directory = "./GameData/Items" for item in items: if item is not None and not load: item_name = self.parser.convert_spaces(item.lower()) item_path = directory + "/{}.json".format(item_name) cur_item = Item.create_item_from_file(item_path) self.inventory.add_item(cur_item) elif item is not None and load: self.inventory = Inventory(items) for obj in features: if obj: cur = Feature(obj["name"], obj["desc"], obj["is_interactive"], obj["interactions"]) self.feature_list.append(cur) def from_file_name(file_name): with open(file_name, encoding="utf-8") as infile: data = json.load(infile) name = data["name"] long_desc = data["long_desc"] short_desc = data["short_desc"] prior_visit = data["prior_visit"] connections = data["connections"] items = data["items"] features = data["features"] return Room(name, long_desc, short_desc, prior_visit, connections, items, features, False) def convert_room_to_json(self): json_inventory = self.inventory.convert_inventory_to_json() json_features = [] for obj in self.feature_list: json_features.append(obj.convert_feature_to_json()) room_data = { "name": self.name, "long_desc": self.long_desc, "short_desc": self.short_desc, "prior_visit": self.prior_visit, "connections": self.connections, "inventory": json_inventory, "feature_list": json_features } return room_data def get_connection(self, num): return self.connections[num] def get_features(self): for obj in self.feature_list: obj.get_feature_info() def examine(self, feature): for obj in self.feature_list: if feature == obj.name: obj.get_desc() break def get_desc(self): if self.prior_visit: print(self.short_desc) else: print(self.long_desc) def get_long_desc(self): print(self.long_desc) def get_short_desc(self): print(self.short_desc) def room_add_item(self, item): self.inventory.add_item(item) def room_drop_item(self, item, player_inventory): for obj in self.inventory.get_inventory_list(): if obj.name.lower() == item: if obj.is_obtainable(): player_inventory.add_item(obj) print( "\nThe Boy grabbed the {} and placed it in his inventory." .format(item)) self.inventory.remove_item(obj) def toggle_visit(self): if not self.prior_visit: self.prior_visit = True
class Healthcheck: IA = {} HOST = '' ip = '' mask = '' inventory = None status = None device = None def __init__(self, host, ip, mask, device): self.device = device self.initIA() self.HOST = host self.ip = ip self.mask = mask self.inventory = Inventory(self.HOST) self.status = Status(self.HOST) def initIA(self): self.IA['ios-type'] = '' self.IA['statut'] = {} self.IA['statut']['cpu'] = {} self.IA['statut']['cpu']['commande'] = {} self.IA['statut']['cpu']['commande'][ 'IOS'] = "show processes cpu sorted 5sec" self.IA['statut']['cpu']['commande'][ 'NX-OS'] = "show processes cpu sort" self.IA['statut']['cpu']['avant'] = [] self.IA['statut']['cpu']['apres'] = [] self.IA['statut']['mem'] = {} self.IA['statut']['mem']['commande'] = {} self.IA['statut']['mem']['commande'][ 'IOS'] = "show processes memory sorted" self.IA['statut']['mem']['commande']['NX-OS'] = "show processes memory" self.IA['statut']['mem']['avant'] = [] self.IA['statut']['mem']['apres'] = [] self.IA['statut']['routes'] = {} self.IA['statut']['routes']['commande'] = {} self.IA['statut']['routes']['commande']['IOS'] = "show ip route" self.IA['statut']['routes']['commande']['NX-OS'] = "show ip route" self.IA['statut']['routes']['avant'] = [] self.IA['statut']['routes']['apres'] = [] self.IA['statut']['ospf'] = {} self.IA['statut']['ospf']['commande'] = {} self.IA['statut']['ospf']['commande']['IOS'] = "show ip ospf neighbor" self.IA['statut']['ospf']['commande'][ 'NX-OS'] = "show ip ospf neighbors" self.IA['statut']['ospf']['avant'] = [] self.IA['statut']['ospf']['apres'] = [] self.IA['statut']['bgp'] = {} self.IA['statut']['bgp']['commande'] = {} self.IA['statut']['bgp']['commande']['IOS'] = "show ip bgp neighbors" self.IA['statut']['bgp']['commande']['NX-OS'] = "show bgp sessions" self.IA['statut']['bgp']['avant'] = [] self.IA['statut']['bgp']['apres'] = [] self.IA['statut']['mpls-ldp'] = {} self.IA['statut']['mpls-ldp']['commande'] = {} self.IA['statut']['mpls-ldp']['commande'][ 'IOS'] = "show mpls ldp neighbor" self.IA['statut']['mpls-ldp']['commande'][ 'NX-OS'] = "show mpls strip labels" self.IA['statut']['mpls-ldp']['avant'] = [] self.IA['statut']['mpls-ldp']['apres'] = [] self.IA['statut']['mpls-te'] = {} self.IA['statut']['mpls-te']['commande'] = {} self.IA['statut']['mpls-te']['commande'][ 'IOS'] = "show mpls traffic-eng tunnels" self.IA['statut']['mpls-te']['commande'][ 'NX-OS'] = "show ip mbgp summary" self.IA['statut']['mpls-te']['avant'] = [] self.IA['statut']['mpls-te']['apres'] = [] self.IA['inventaire'] = {} self.IA['inventaire']['commande'] = {} self.IA['inventaire']['commande']['IOS'] = "show inventory" self.IA['inventaire']['commande']['NX-OS'] = "show inventory" self.IA['inventaire']['avant'] = [] self.IA['inventaire']['apres'] = [] self.IA['version'] = {} self.IA['version']['OS'] = {} self.IA['version']['IMAGE'] = {} self.IA['version']['REGISTER'] = {} self.IA['version']['IOS'] = {} self.IA['version']['commande'] = {} self.IA['version']['avant'] = [] self.IA['version']['apres'] = [] self.IA['version']['OS']['avant'] = "" self.IA['version']['OS']['apres'] = "" self.IA['version']['IMAGE']['avant'] = "" self.IA['version']['IMAGE']['apres'] = "" self.IA['version']['REGISTER']['avant'] = "" self.IA['version']['REGISTER']['apres'] = "" self.IA['version']['IOS']['avant'] = "" self.IA['version']['IOS']['apres'] = "" self.IA['version']['commande']['IOS'] = "show version" self.IA['version']['commande']['NX-OS'] = "show version" self.IA['register'] = {} self.IA['register']['commande'] = {} self.IA['register']['config'] = "0x2102" self.IA['register']['commande'][ 'IOS'] = "config-register " + self.IA['register']['config'] self.IA['boot'] = {} self.IA['boot']['commande'] = {} self.IA['boot']['commande']['IOS'] = "boot system " self.IA['storage'] = {} self.IA['storage']['commande'] = {} self.IA['storage']['suppress'] = {} self.IA['storage']['upload'] = {} self.IA['storage']['avant'] = {} self.IA['storage']['apres'] = {} self.IA['storage']['upgrade'] = "" self.IA['storage']['upgrade_system'] = {} self.IA['storage']['upgrade_system']['avant'] = None self.IA['storage']['upgrade_system']['apres'] = None self.IA['storage']['commande']['IOS'] = "dir /all /recursive" # self.IA['storage']['commande']['IOS'] = "dir all-filesystems" self.IA['storage']['commande']['NX-OS'] = "dir all-filesystems" self.IA['storage']['suppress'][ 'IOS'] = "delete <BACKUP_STORE><BACKUP_FILE>" # self.IA['storage']['suppress']['IOS'] = "delete /force <BACKUP_STORE><BACKUP_FILE>" self.IA['storage']['upload'][ 'IOS'] = "copy <BACKUP_SITE><BACKUP_FILE> <BACKUP_STORE><BACKUP_FILE>" self.IA['interface'] = {} self.IA['interface']['upgrade'] = {} self.IA['interface']['upgrade']['device'] = "" self.IA['interface']['upgrade']['station'] = "" self.IA['interface']['commande'] = {} self.IA['interface']['commande'][ 'IOS'] = "show running interface <INTERFACE_NAME>" self.IA['interface']['commande'][ 'NX-OS'] = "show running interface <INTERFACE_NAME>" self.IA['interface']['avant'] = [] self.IA['interface']['apres'] = [] self.IA['interfaces'] = {} self.IA['interfaces']['commande'] = {} self.IA['interfaces']['commande']['IOS'] = "show ip interface brief" self.IA['interfaces']['commande'][ 'IOS-XR'] = "show ipv4 interface brief" self.IA['interfaces']['avant'] = [] self.IA['interfaces']['apres'] = [] self.IA['save'] = {} self.IA['save']['commande'] = {} self.IA['save']['commande']['IOS'] = "write" self.IA['save']['commande']['NX-OS'] = "" self.IA['save']['commande']['IOS-XE'] = "copy ru st" self.IA['md5'] = {} self.IA['md5']['commande'] = {} self.IA['md5']['commande']['IOS'] = "verify /md5 <FICHIER>" self.IA['md5']['commande']['IOS-XE'] = "sam verify <FICHIER> MD5" self.IA['md5']['commande']['IOS-XR'] = "show md5 file /<FICHIER>" self.IA['md5']['commande']['NX-OS'] = "show file <FICHIER> md5sum" self.IA['config'] = {} self.IA['config']['last'] = "" self.IA['config']['backup'] = {} self.IA['config']['replace'] = {} self.IA['config']['update'] = {} # NOT IMPLEMENTED # self.IA['config']['replace']['IOS'] = [ # "copy <BACKUP_SITE><BACKUP_FILE> <BACKUP_STORE><BACKUP_FILE>", # TO LOCAL DEVICE STORAGE for later md5 # "configure replace <BACKUP_STORE><BACKUP_FILE> force time 5", # TO BACKUP SERVICE and confirm md5 with # "configure confirm", # "configure revert now" # ] # # self.IA['config']['backup']['IOS-XE'] = [ # ] # self.IA['config']['replace']['IOS-XE'] = [ # ] # self.IA['config']['update']['IOS-XE'] = [ # ] # # self.IA['config']['backup']['NX-OS'] = [ # ] # self.IA['config']['replace']['NX-OS'] = [ # ] # self.IA['config']['update']['NX-OS'] = [ # ] # IMPLEMENTED self.IA['config']['backup']['IOS'] = [ "copy running-config <BACKUP_SITE><BACKUP_FILE>", # TO BACKUP SERVICE and confirm md5 with "copy running-config <BACKUP_STORE><BACKUP_FILE>" # TO LOCAL DEVICE STORAGE for later md5 ] self.IA['config']['update']['IOS'] = [ "copy <BACKUP_SITE><BACKUP_FILE> <BACKUP_STORE><BACKUP_FILE>", # TO LOCAL DEVICE STORAGE for later md5 "copy <BACKUP_STORE><BACKUP_FILE> running-config" # TO BACKUP SERVICE and confirm md5 with ] def get_config_register(self, when='avant', echo=False): return self.IA['version']['REGISTER'][when] def get_default_config_register(self): return self.IA['register']['config'] def prepare_configuration(self, config='', echo=False): retour = [] if echo: print("# Preparation de la configuration") retour.append("configure terminal") retour.append(config) retour.append("end") return retour def configure_bootflag(self, when, dst, file, echo=False): command = "" OS = self.IA['version']['OS'][when] buffer = "" dst = dst.replace('/', '') try: command = self.IA['boot']['commande'][OS] except Exception as e: print("# Commande non connue pour ce OS: " + str(e)) print("# Utilisation de la commande standard d'un IOS") command = self.IA['register']['commande']['IOS'] if command != "": if echo: print("# Envoi de la commande de registre sur l'equipement: ") print("# ".join(command)) print() command = command + dst + file buffer = self.device.execute(self.prepare_configuration(command), echo) if echo: print("# Affichage de la reception du boot system:") print(buffer) print() buffer = buffer.replace('#', '') buffer = buffer.replace('\r', '') buffer = buffer.replace('\n', '') print("# Affichage de la reception du boot system:") print(buffer) print() self.save(when) buffer = '' return self.process_config_bootflag(buffer) def process_config_bootflag(self, buffer): buffer = buffer.replace('#', '') buffer = buffer.replace('\r', '') buffer = buffer.replace('\n', '') return buffer == '' def configure_register(self, when, echo=False): command = "" OS = self.IA['version']['OS'][when] buffer = "" try: command = self.IA['register']['commande'][OS] except Exception as e: print("# Commande non connue pour ce OS: " + str(e)) print("# Utilisation de la commande standard d'un IOS") command = self.IA['register']['commande']['IOS'] if command != "": if echo: print("# Envoi de la commande de registre sur l'equipement: ") print("# ".join(command)) print() buffer = self.device.execute(self.prepare_configuration(command), echo) if echo: print("# Affichage de la reception de la registre:") print("# ".join(buffer)) print() self.save(when) return self.process_config_register(buffer) def process_config_register(self, buffer): return buffer == '' def save(self, when, echo=False): command = "" OS = self.IA['version']['OS'][when] buffer = "" try: command = self.IA['save']['commande'][OS] except Exception as e: print("# Commande non connue pour ce OS: " + str(e)) print("# Utilisation de la commande standard d'un IOS") command = self.IA['save']['commande']['IOS'] if command != "": if echo: print( "# Envoi de la commande de sauvegarde sur l'equipement: ") print("# ".join(command)) print() buffer = self.device.execute([command], echo) if echo: print("# Affichage de la reception de sauvegarde") print("# ".join(buffer)) print() return self.process_save(buffer) def process_save(self, buffer): return buffer == '' def suppress(self, when, dst, file, echo=False): command = "" OS = self.IA['version']['OS'][when] buffer = "" dst = dst.replace('\r', '') file = file.replace('\r', '') dst = dst.replace('\r', '') file = file.replace('\r', '') try: command = self.IA['storage']['suppress'][OS] except Exception as e: print("# Commande non connue pour ce OS: " + str(e)) print("# Utilisation de la commande standard d'un IOS") command = self.IA['storage']['suppress']['IOS'] if command != "": # Rfile = file.split('/') # if len(Rfile) > 0: # file = Rfile[0] command = re.sub(r'<BACKUP_FILE>', file, command) command = re.sub(r'<BACKUP_STORE>', dst, command) if echo: print("# Envoi de la commande suivante pour upload: ") print("# ".join(command)) print() buffer = self.device.execute([command], echo) if echo: print("# Affichage de la reception de la supression:") print("# ".join(buffer)) print() return self.process_suppress(buffer) def process_suppress(self, buffer): return buffer == '' def upload(self, when, src, dst, file, echo=False): retour = True command = "" OS = self.IA['version']['OS'][when] buffer = "" src = src.replace('\n', '') dst = dst.replace('\n', '') file = file.replace('\n', '') src = src.replace('\r', '') dst = dst.replace('\r', '') file = file.replace('\r', '') # dst += '/' if echo: print("# Fichier: " + file) print("# Source: " + src) print("# Destination: " + dst) try: command = self.IA['storage']['upload'][OS] except Exception as e: print("# Commande non connue pour ce OS: " + str(e)) print("# Utilisation de la commande standard d'un IOS") command = self.IA['storage']['upload']['IOS'] if command != "": file = file.strip("\n") command = re.sub(r'<BACKUP_FILE>', file, command) command = re.sub(r'<BACKUP_STORE>', dst, command) command = re.sub(r'<BACKUP_SITE>', src, command) if echo: print("# Envoi de la commande suivante pour upload: ") print(command) print() buffer = self.device.execute([command], echo) if echo: print("# Affichage de la reception du televersement:") print(buffer) print() if not self.process_upload(buffer): retour = False print(buffer) print() return retour def process_upload(self, buffer): return buffer == '' def get_local_file_size(self, file): return int(os.path.getsize(file)) def get_remote_file_size(self, when, fsystem): size = self.IA['storage'][when][fsystem].get('size') if size is not None: return int(size) else: return 0 def get_remote_filesystem_size(self, when, fsystem): size = self.IA['storage'][when][fsystem]['size'] if size is not None: return int(size) else: return 0 def get_remote_filesystem_left(self, when, fsystem): size = None try: size = self.IA['storage'][when][fsystem]['left'] except: fsystem = fsystem.replace('/', '') size = self.IA['storage'][when][fsystem]['left'] if size is not None: return int(size) else: return 0 def get_config_choice(self, when='avant', folder="./fichiers"): retour = [] # keys = list(self.IA['storage'][when].keys()) files = list([f for f in os.listdir(folder) if f.endswith('.cfg')]) k = [] i = 0 for file in files: choice = file retour.append(choice) k.append(str(i)) i += 1 return k, retour def get_ios_choice(self, when='avant'): retour = [] keys = list(self.IA['storage'][when].keys()) k = [] i = 0 for key in keys: bins = self.IA['storage'][when][key]['bins'] for binfile in bins: choice = key + binfile retour.append(choice) k.append(str(i)) i += 1 return k, retour def get_storage_choice(self, when='avant'): retour = [] keys = list(self.IA['storage'][when].keys()) for key in keys: left = self.IA['storage'][when][key]['left'] size = self.IA['storage'][when][key]['size'] choice = key + ", " + str(left) + " octets restants sur " + str( size) retour.append(choice) return keys, retour def config(self, when, operation, iteration, src, dst, file, folder, echo=False, test=False): command = "" OS = self.IA['version']['OS'][when] buffer = "" src = src.replace("\n", "") dst = dst.replace("\n", "") file = file.replace("\n", "") src = src.replace("\r", "") dst = dst.replace("\r", "") file = file.replace("\r", "") file = file.replace("\r", "") try: command = self.IA['config'][operation][OS][iteration] except Exception as e: print("# Commande non connue pour ce OS: " + str(e)) print("# Utilisation de la commande standard d'un IOS") command = self.IA['config'][operation]['IOS'][iteration] if command != "": command = re.sub(r'<BACKUP_FILE>', file, command) if operation == 'backup': command = re.sub(r'<BACKUP_STORE>', dst, command) command = re.sub(r'<BACKUP_SITE>', dst, command) elif operation == 'update': command = re.sub(r'<BACKUP_STORE>', dst, command) command = re.sub(r'<BACKUP_SITE>', src, command) elif operation == 'replace': if echo: print("# Config 'replace' en construction...") if echo: print("# Envoi de la commande suivante pour " + operation + ": ") print(command) print() buffer = self.device.execute([command], echo) if echo: print( "# Affichage de la reception de l'operation sur la configuration:" ) print(buffer) print() if not test: self.IA['config']['last'] = file return self.process_config(buffer) def process_config(self, buffer): return buffer == '' def md5sum(self, when, file, echo=False): OS = self.IA['version']['OS'][when] buffer = "" md5command = "" try: md5command = self.IA['md5']['commande'][OS] except Exception as e: print("# Commande non connue md5sum pour ce OS: " + str(e)) print("# Utilisation de la commande standard d'un IOS") md5command = self.IA['md5']['commande']['IOS'] if md5command != "": md5command = re.sub(r'<FICHIER>', file, md5command) if echo: print( "# Envoi de la commande suivante pour obtenir la verification MD5:" ) print(md5command) print("\n") buffer = self.device.execute([md5command], echo) return self.process_md5(buffer, echo) def process_md5(self, buffer, echo=False): md5 = "" for line in buffer.splitlines(): if echo: print("# *** MD5 recu: " + line) if re.match(r".+ = .+", line) is not None: if echo: print("# *** MD5 match: " + line) md5 = line.split('=')[1] md5 = md5.strip(' ') if echo: print("# *** MD5 est: " + md5) break if echo: print("# *** MD5 retour: " + md5) return md5 def getios(self): print("# Telechargement du IOS (download)") def putios(self): print("# Televersement du IOS (upload)") def print_storage(self, when, which, echo=False): storage = self.IA['storage'][when] left = str(storage[which]['left']) total = str(storage[which]['size']) print("# " + which + " => espace libre: " + left + " octets, espace totale: " + total + " octets") if len(storage[which]['bins']) > 0: print("# ******** Binaire(s) sur ce systeme: ") print("# ******** --------------------------") print("# ******** " + " , ".join(storage[which]['bins'])) # print() def process_all_storage(self, buffer, echo=False): retour = {} fsystem = '' lastfsystem = '' if echo: print("# Storage, recu") # print("# ".join(buffer)) print(buffer) print() for line in buffer.splitlines(): if re.match('Directory of', line): fsystem = line.split(' ')[2] Rfsystem = fsystem.split('/') fsystem = Rfsystem[0] path = '' if len(Rfsystem) > 0: path = Rfsystem[1] path = path.replace('*', '') if path != '': path = path + '/' fsystem = fsystem + '/' fsystem = fsystem.replace('\n', '') fsystem = fsystem.replace('\"', '') fsystem = fsystem.replace(' ', '') fsystem = fsystem.replace('*', '') if lastfsystem != fsystem: lastfsystem = fsystem retour[fsystem] = {} retour[fsystem]['bins'] = [] retour[fsystem]['bins-sizes'] = [] retour[fsystem]['size'] = 0 retour[fsystem]['left'] = 0 retour[fsystem]['content'] = [] # if fsystem == 'flash:/': # self.IA['storage']['upgrade_system'] = fsystem #.replace('/','') if fsystem != '': if line == '': continue if echo: print("# Systeme de fichier: " + fsystem) print("# Path: " + path) if re.match(r".*bytes total", line): total = re.findall(r"(.*?) bytes total", line)[0] if total != '' or total > 0: retour[fsystem]['size'] = int(total) if re.match(r".*bytes free", line): free = re.findall(r"\((.*?) bytes free", line)[0] if free != '' or free > 0: retour[fsystem]['left'] = int(free) if re.match(r".*\.bin", line): binaryfile = line.split()[-1] binarysize = line.split()[2] if echo: print("# Fichier binaire: " + binaryfile) print("# Taille fichier: " + binarysize) retour[fsystem]['bins'].append(path + binaryfile) retour[fsystem]['bins-sizes'].append(int(binarysize)) retour[fsystem]['content'].append(line) # else: # print("# *** Impossible de poursuivre la lecture du filesystem, fsystem vide: "+fsystem) return retour def checkallstorage(self, when='avant', echo=False): if echo: print("# Lecture de tous les type de storage: ") os = self.IA['version']['OS']['avant'] command = self.IA['storage']['commande'][os] # command = "dir all-filesystems" buffer = self.device.execute([command], echo) if echo: print("# Recu:") # print("# ".join(buffer.splitlines)) print(buffer) print() self.IA['storage'][when] = self.process_all_storage(buffer, echo) def askinterface(self, who, where, os, echo=False): interface = '' interfaces = self.getinterfaces(where, os, False) l = [str(j) for j in range(len(interfaces))] i = who.askchoice( "# Choisir l'interface qui servira pour telecharger ou televerser les fichiers par le reseau:", l, interfaces) interface = interfaces[i].split()[0] print("# L'index choisi: " + str(i) + " correspond a l'interface: " + interface) # if who.askyesno( "# Voulez-vous identier visuellement l'interface ? Si oui, elle devrait clignoter rapidement pendant les 10 prochaines secondes"): # self.blinkinterface(interface) who.askyesno("# Voulez-vous continuer avec cette interface ?") return interface def blinkinterface(self, interface): print("#") def getinterfaces(self, where='device', os='Linux', echo=False): if where == 'device': # print("# Choisir l'interface qui servira pour telecharger ou televerser les fichiers par le reseau:") commande = '' if os == 'NX-OS' or os == "IOS-XR" or os == 'IOS-XE': commande = self.IA['interfaces']['commande'][os] else: commande = self.IA['interfaces']['commande']['IOS'] # buffer = self.device.execute([commande], True).splitlines() buffer = self.device.execute([commande], echo) if echo: print("# Recu de l'execution de la commande:") print("# ".join(buffer)) print() interfaces = [] gotinterface = False for line in buffer.splitlines(): if line == '': continue if re.match(r'Interface', line): gotinterface = True else: if gotinterface: interfaces.append(line) if echo: print("# Interfaces sur l'equipement:") print("# ".join(interfaces)) print() return interfaces else: #STATION print("# En construction: ask interface, else for station") def getinterfaceconfig(self, who, where, when, echo=False): OS = self.IA['version']['OS'][when] buffer = "" # interface = 'FastEthernet 0' interface = self.askinterface(who, where, OS, echo) interfaceconfig = "" self.IA['interface']['upgrade'][where] = interface if (OS == 'NX-OS'): interfaceconfig = self.IA['interface']['commande'][OS] interfaceconfig = re.sub(r'<INTERFACE_NAME>', interface, interfaceconfig) if echo: print( "# Envoi de la commande suivante pour obtenir la configuration de l'interface a configurer:" ) print("# ".join(interfaceconfig)) print() else: interfaceconfig = self.IA['interface']['commande']['IOS'] interfaceconfig = re.sub(r'<INTERFACE_NAME>', interface, interfaceconfig) if echo: print( "# Envoi de la commande suivante pour obtenir la configuration de l'interface a configurer:" ) print("# ".join(interfaceconfig)) print() buffer = self.device.execute([interfaceconfig], echo) config = self.process_interface('interface', buffer) try: self.IA['interface'][when].append(config) # if len(['interface'][when]) == 0: # self.IA['interface'][when].append() # # self.IA['interface'][when][0] = config except: # self.IA['interface'][when].append("L'equipement ne retourne pas d'informations sur l'interface:"+interface) self.IA['interface'][when].append( "Cet operation ne retourne pas d'informations sur l'interface:" + interface) def process_interface(self, category, buffer): retour = "" # print("# Analyse de la configuration de l'interface pour la categorie: "+category) # print("# ".join(buffer)) # print() currentfound = False for line in buffer.splitlines(): if re.match('Current', line): currentfound = True elif currentfound: retour += line retour += '\n' if re.match('end', line): break # print("# Retour") # print(retour) return retour def configureinterface(self, when, what, ip, mask, echo=False): try: interface = '' if what == 'device': interface = self.IA['interface']['upgrade'][what] config = self.prepare_interface_configuration( what, ip, mask, echo, interface) # print("\n".join(config)) if echo: print("# Configuration de l'interface qui sera envoyee") print("# ".join(config)) buffer = self.device.execute(config, echo) # print(buffer) if echo: print("# Recu par la configuration de l'interface:") print("# ".join(buffer)) print() if buffer.find('L2') > 0: # print("# *** Ajustement de la configuration pour un no switchport") # buffer = self.device.execute(config, echo) return False else: self.save(when) return True except Exception as e: print("# *** Exception recu: " + str(e)) return False def prepare_interface_configuration(self, what, ip, mask, echo=False, interface=''): retour = [] if echo: print("# Configuration de l'interface") retour.append("configure terminal") retour.append("interface " + interface) OS = self.IA['version']['OS']['avant'] # print("# L2 DETECTED...") # print(self.IA['version']['avant']) L2 = self.IA['version']['avant'][0]['L2'] # print("# L2 DETECTED: "+str(L2)) if L2: retour.append("no switchport") if (OS == 'IOS-XR') or (OS == 'IOS-XE'): retour.append("ipv4 address " + ip + ' ' + mask) else: retour.append("ip address " + ip + ' ' + mask) retour.append("no shutdown") retour.append("end") return retour def rollbackinterface(self, echo=False): try: if len(self.IA['interface']['avant']) > 0: print( "# Retour en arriere sur la configuration de l'interface") config = self.prepare_interface_rollback() if echo: print("# ".join(config)) print() print(self.device.execute(config, False)) return True except Exception as e: print("# *** Exception recu: " + str(e)) return False def prepare_interface_rollback(self): retour = [] retour.append("configure terminal") retour.append(self.IA['interface']['avant'][0]) return retour def healthCheck(self, when): # self.checkCpu(when) # self.checkMem(when) self.checkRoutes(when) self.checkOspf(when) self.checkBgp(when) self.checkMplsLdp(when) self.checkMplsTe(when) def print_status(self, category='cpu', when='avant', iteration=0): print('# Affichage statut ' + category) print(json.dumps(self.IA['statut'][category][when][iteration])) def print_health(self, when='avant', iteration=0): # how = 'status' # how = 'raw' how = 'top' # self.print_health_what('cpu',when,iteration,'top') # self.print_health_what('mem', when, iteration, 'top') self.print_health_what('routes', when, iteration, 'raw') self.print_health_what('ospf', when, iteration, 'raw') self.print_health_what('bgp', when, iteration, 'raw') self.print_health_what('mpls-ldp', when, iteration, 'raw') self.print_health_what('mpls-te', when, iteration, 'raw') def print_health_what(self, what='cpu', when='avant', iteration=0, how='status'): print() print( '#--------------------------------------------------------------------------------------------' ) print('# ' + self.HOST + ': ' + what + ', ' + when + ', iteration #' + str(iteration)) print( '#--------------------------------------------------------------------------------------------' ) print() if how == 'status': print('\n'.join(self.IA['statut'][what][when][iteration])) elif how == 'raw': print('\n'.join(self.IA['statut'][what][when][iteration]['raw'])) elif how == 'top': print('\n'.join(self.IA['statut'][what][when][iteration]['top'])) def print_raw(self, category='cpu', when='avant', iteration=0): print(json.dumps(self.IA[category][when][iteration]['raw'])) def print_top(self, category='cpu', when='avant', iteration=0): print(json.dumps(self.IA[category][when][iteration]['top'])) def checkRoutes(self, when='avant'): # buffer = self.device.execute([self.IA['statut']['mem']['commande']]) buffer = "" OS = self.IA['version']['OS'][when] if (OS == 'NX-OS'): buffer = self.device.execute( [self.IA['statut']['routes']['commande'][OS]]) else: buffer = self.device.execute( [self.IA['statut']['routes']['commande']['IOS']]) self.status.process_raw_topN('routes', buffer, 20) try: self.IA['statut']['routes'][when].append( self.status.INV[self.HOST]['routes']) except: self.IA['statut']['routes'][when].append( "L'equipement ne retourne pas d'informations sur l'utilisation mem des processus" ) def checkCpu(self, when): # print("Reception des donnees du cpu "+when) buffer = "" OS = self.IA['version']['OS'][when] if (OS == 'NX-OS'): buffer = self.device.execute( [self.IA['statut']['cpu']['commande'][OS]]) else: buffer = self.device.execute( [self.IA['statut']['cpu']['commande']['IOS']]) # self.status.process_cpu(buffer) self.status.process_raw_topN('cpu', buffer, 20) try: self.IA['statut']['cpu'][when].append( self.status.INV[self.HOST]['cpu']) except: self.IA['statut']['cpu'][when].append( "L'equipement ne retourne pas d'informations sur l'utilisation cpu" ) def checkMem(self, when): # buffer = self.device.execute([self.IA['statut']['mem']['commande']]) buffer = "" OS = self.IA['version']['OS'][when] if (OS == 'NX-OS'): buffer = self.device.execute( [self.IA['statut']['mem']['commande'][OS]]) else: buffer = self.device.execute( [self.IA['statut']['mem']['commande']['IOS']]) # self.status.process_mem(buffer) self.status.process_raw_topN('mem', buffer, 20) try: self.IA['statut']['mem'][when].append( self.status.INV[self.HOST]['mem']) except: self.IA['statut']['mem'][when].append( "L'equipement ne retourne pas d'informations sur l'utilisation mem des processus" ) def checkOspf(self, when): # buffer = self.device.execute([self.IA['statut']['ospf']['commande']]) buffer = "" OS = self.IA['version']['OS'][when] if (OS == 'NX-OS'): buffer = self.device.execute( [self.IA['statut']['ospf']['commande'][OS]]) else: buffer = self.device.execute( [self.IA['statut']['ospf']['commande']['IOS']]) # self.status.process_ospf(buffer) self.status.process_raw_topN('ospf', buffer, 20) try: self.IA['statut']['ospf'][when].append( self.status.INV[self.HOST]['ospf']) except: self.IA['statut']['ospf'][when].append( "L'equipement ne retourne pas d'informations sur ospf") def checkBgp(self, when): # buffer = self.device.execute([self.IA['statut']['bgp']['commande']]) buffer = "" OS = self.IA['version']['OS'][when] if (OS == 'NX-OS'): buffer = self.device.execute( [self.IA['statut']['bgp']['commande'][OS]]) else: buffer = self.device.execute( [self.IA['statut']['bgp']['commande']['IOS']]) self.status.process_raw_topN('bgp', buffer, 20) try: self.IA['statut']['bgp'][when].append( self.status.INV[self.HOST]['bgp']) except: self.IA['statut']['bgp'][when].append( "L'equipement ne retourne pas d'informations sur bgp") def checkMplsLdp(self, when): # buffer = self.device.execute([self.IA['statut']['mpls-ldp']['commande']]) buffer = "" OS = self.IA['version']['OS'][when] if (OS == 'NX-OS'): buffer = self.device.execute( [self.IA['statut']['mpls-ldp']['commande'][OS]]) else: buffer = self.device.execute( [self.IA['statut']['mpls-ldp']['commande']['IOS']]) self.status.process_raw_topN('mpls-ldp', buffer, 20) try: self.IA['statut']['mpls-ldp'][when].append( self.status.INV[self.HOST]['mpls-ldp']) except: self.IA['statut']['mpls-ldp'][when].append( "L'equipement ne retourne pas d'informations sur mpls-ldp") def checkMplsTe(self, when): # buffer = self.device.execute([self.IA['statut']['mpls-te']['commande']) buffer = "" OS = self.IA['version']['OS'][when] if (OS == 'NX-OS'): buffer = self.device.execute( [self.IA['statut']['mpls-te']['commande'][OS]]) else: buffer = self.device.execute( [self.IA['statut']['mpls-te']['commande']['IOS']]) self.status.process_raw_topN('mpls-te', buffer, 20) try: self.IA['statut']['mpls-te'][when].append( self.status.INV[self.HOST]['mpls-te']) except: self.IA['statut']['mpls-te'][when].append( "L'equipement ne retourne pas d'informations sur mpls-te") def checkInventory(self, when): buffer = "" OS = self.IA['version']['OS'][when] if (OS == 'NX-OS'): buffer = self.device.execute( [self.IA['inventaire']['commande'][OS]]) else: buffer = self.device.execute( [self.IA['inventaire']['commande']['IOS']]) # print('Traitement inventaire recu') self.inventory.process_inventory2(buffer, self.device.prompt) # print('Affichage inventaire recu') # self.inventory.inventory_print() try: self.IA['inventaire'][when].append( self.inventory.INV[self.HOST]['inventory']) except: self.IA['inventaire'][when].append( "L'equipement ne retourne pas d'inventaire") def print_inventory(self, when='avant', iteration=0): print() print( '#--------------------------------------------------------------------------------------------' ) print('# ' + self.HOST + ': ' + 'Inventaire' + ', ' + when + ', iteration #' + str(iteration)) print( '#--------------------------------------------------------------------------------------------' ) print() print(json.dumps(self.IA['inventaire'][when][iteration])) print() def checkVersion(self, when, echo=False): retour = False commande = self.IA['version']['commande']['IOS'] buffer = self.device.execute([commande], echo) (self.IA['version']['OS'][when], self.IA['version']['REGISTER'][when], image) = self.inventory.process_version3(buffer, echo) if re.match(r".+:", image) is not None: imageset = image.split(':') if echo: print(imageset) self.IA['storage']['upgrade_system'][when] = imageset[0] + ':/' # self.IA['storage']['upgrade_system'][when] = imageset[0] + ':/' self.IA['version']['IMAGE'][when] = imageset[1] retour = True else: # if echo: print("# *** Le format du fichier image recu est non support") print("# *** Fin des travaux") print("# *** Fichier: " + str(image)) retour = False try: self.IA['version'][when].append( self.inventory.INV[self.HOST]['version']) except: self.IA['version'][when].append( "L'equipement ne retourne pas d'informations sur la version") return retour def print_os(self, when='avant'): print() print( '#--------------------------------------------------------------------------------------------' ) print('# ' + self.HOST + ': ' + 'OS' + ', ' + when) print( '#--------------------------------------------------------------------------------------------' ) print("# SYSTEME D'EXPLOITATION : " + self.IA['version']['OS'][when]) print("# REGISTRE DE CONFIGURATION : " + self.IA['version']['REGISTER'][when]) print("# IMAGE AU DEMARRAGE : " + self.IA['version']['IMAGE'][when]) print("# SYSTEME DE FICHIERS : " + self.IA['storage']['upgrade_system'][when]) print( '#--------------------------------------------------------------------------------------------' ) print() def print_version(self, when='avant', iteration=0): print() print( '#--------------------------------------------------------------------------------------------' ) print('# ' + self.HOST + ': ' + 'Version' + ', ' + when + ', iteration #' + str(iteration)) print( '#--------------------------------------------------------------------------------------------' ) print() print(json.dumps(self.IA['version'][when][iteration])) print()
def __init__(self, _client): global players global players_lock self.client = _client self.health = 100 self.dead = False self.name = "Unknown" self.speed = 12.0 self.dropout_time = 0 self.last_packet_id = 0 self.sent_packet_id = 0 # generate random player id and add it to the list # TODO make player id count from 0-inf incremented (like prop_id) with player_id_count_lock: global player_id_count player_id_count += 1 self.player_id = player_id_count with players_lock: players[self.player_id] = self self.inventory = Inventory() print("player initiated, id:{}".format(self.player_id)) self.add_cheat_items_for_testing() print("player cheat items, id:{}".format(self.player_id)) # physics stuff self.body = None self.shape = None self.body = pymunk.Body(10, pymunk.inf) self.shape = pymunk.Circle(self.body, 0.58) self.shape.elasticity = 0 self.shape.collision_type = physics.collision_types["player"] player_shape_to_player[self.shape] = self with players_lock: self.create_body() # Give default names depending if player is bot or not if self.client is None: self.name = "Bot - {}".format(self.player_id - 10000) else: self.name = "Player - {}".format(self.player_id - 10000) global total_player_count global alive_player_count with total_player_count_lock: total_player_count += 1 with alive_player_count_lock: alive_player_count += 1 self.time_since_last_movement = 0 print("player body initiated, id:{}".format(self.player_id))
class Player: def __init__(self, _client): global players global players_lock self.client = _client self.health = 100 self.dead = False self.name = "Unknown" self.speed = 12.0 self.dropout_time = 0 self.last_packet_id = 0 self.sent_packet_id = 0 # generate random player id and add it to the list # TODO make player id count from 0-inf incremented (like prop_id) with player_id_count_lock: global player_id_count player_id_count += 1 self.player_id = player_id_count with players_lock: players[self.player_id] = self self.inventory = Inventory() print("player initiated, id:{}".format(self.player_id)) self.add_cheat_items_for_testing() print("player cheat items, id:{}".format(self.player_id)) # physics stuff self.body = None self.shape = None self.body = pymunk.Body(10, pymunk.inf) self.shape = pymunk.Circle(self.body, 0.58) self.shape.elasticity = 0 self.shape.collision_type = physics.collision_types["player"] player_shape_to_player[self.shape] = self with players_lock: self.create_body() # Give default names depending if player is bot or not if self.client is None: self.name = "Bot - {}".format(self.player_id - 10000) else: self.name = "Player - {}".format(self.player_id - 10000) global total_player_count global alive_player_count with total_player_count_lock: total_player_count += 1 with alive_player_count_lock: alive_player_count += 1 self.time_since_last_movement = 0 print("player body initiated, id:{}".format(self.player_id)) # Get Move request # Speed check if movement is possible # Move body def move_request(self, packet_id, pos_x, pos_y, angle): if self.last_packet_id > int(packet_id): return else: self.last_packet_id = int(packet_id) try: self.check_speed_and_move(pos_x, pos_y, angle) except: print("Error: Can not parse position info. Playerid:{} ".format( self.player_id)) def check_speed_and_move(self, pos_x, pos_y, angle): if self.dead: return movement_threshold = ( (timeit.default_timer() - self.time_since_last_movement) * self.speed) distance_between_positions = sqrt(( (float(pos_x) - self.body.position[0])**2) + ( (float(pos_y) - self.body.position[1])**2)) if distance_between_positions <= movement_threshold: self.move_body(pos_x, pos_y, angle) else: if self.client is not None: to_reply = "MOVRJ:{},{};".format(self.body.position[0], self.body.position[1]) self.client.send(to_reply) self.time_since_last_movement = timeit.default_timer() def move_body(self, pos_x, pos_y, angle): self.body.position = Vec2d(float(pos_x), float(pos_y)) self.body.angle = radians(float(angle)) def add_cheat_items_for_testing(self): with item.item_id_lock: item.item_id_counter += 1 weapon_id = item.item_id_counter # Add pistol item_type = 1001 self.inventory.add_item(weapon_id, item_type) self.inventory.equip_item_to_main_hand(weapon_id) # self.current_weapon_in_hand = self.inventory.equipped_items[weapon_id] # print("Weapon with weapon_id:{} and weapon_type:{} is currenty equipped in main hand".format( # self.current_weapon_in_hand.item_id, self.current_weapon_in_hand.item_type_id)) def shoot(self): if self.dead: return weapon_type_id = self.inventory.main_hand_item.item_type_id if self.inventory.ammo_nine_mm_count <= 0: return self.inventory.ammo_nine_mm_count -= 1 speed = 1 damage = 0 if weapon_type_id == 1001: speed = 15 damage = 55 elif weapon_type_id == 1002: speed = 15 damage = 20 # Maybe player died after coming into this method, then body_position will be None, check for this if not self.dead: bullet.Bullet(self.player_id, self.body.position[0], self.body.position[1], degrees(self.body.angle), speed, damage) def on_bullet_hit(self, bullet_obj): self.health -= bullet_obj.damage print('got hit! ' + str(self.health)) if self.health < 0: self.killed(bullet_obj) def killed(self, cause_of_death): self.health = 0 self.dead = True print("im dead as {}".format(self.name)) # send info to clients # death_message = "" if isinstance(cause_of_death, bullet.Bullet): weapon_used = player.players.get( cause_of_death.player_id).inventory.get_weapon_used() killer_player_name = player.players.get( cause_of_death.player_id).name death_message = "KILED:{},{},{},{},{};".format( self.player_id, self.name, cause_of_death.player_id, killer_player_name, weapon_used) else: weapon_used = "Magic" death_message = "KILED:{},{},{},{},{};".format( self.player_id, self.name, 0, "Mother Nature", weapon_used) client.send_death_info_to_all_players(death_message) with physics.physics_lock: physics.space.remove(self.body, self.shape) game.on_player_killed() def create_body(self): self.body = pymunk.Body(500, pymunk.inf) self.shape = pymunk.Circle(self.body, 0.55) self.shape.elasticity = 0 self.shape.collision_type = physics.collision_types["player"] player_shape_to_player[self.shape] = self with physics.physics_lock: physics.space.add(self.body, self.shape) # self.body.position = Vec2d(random.uniform(-100, 100), random.uniform(-100, 100)) self.body.position = Vec2d(random.uniform(-5, 5), random.uniform(-5, 5)) def pickup_item(self, pickup_id): if not self.dead: picked_pickup: pickup.Pickup = pickup.pickups[pickup_id] print("Pickup item and quantity:{}, {}".format( pickup_id, picked_pickup.quantity)) if picked_pickup.item_type == 5009: self.inventory.ammo_nine_mm_count += picked_pickup.quantity elif picked_pickup.item_type == 1001: with item.item_id_lock: item.item_id_counter += 1 item_id = item.item_id_counter self.inventory.add_item(item_id, picked_pickup.item_type) picked_pickup.pickup_id with pickup.pickup_lock: deleted_pickup_info = "PCKDL:{};".format(pickup_id) deleted_pickup_pos_x = picked_pickup.body.position[0] deleted_pickup_pos_y = picked_pickup.body.position[1] with physics.physics_lock: physics.space.remove(picked_pickup.body, picked_pickup.shape) del pickup.pickups[pickup_id] # print(deleted_pickup_info + str(deleted_pickup_pos_x) + str(deleted_pickup_pos_y)) client.send_message_to_nearby_clients(deleted_pickup_pos_x, deleted_pickup_pos_y, deleted_pickup_info)