def main(): log(Config.APP_TITLE, color='blue', figlet=True) log(Config.WELCOME_MSG, color='green') cred = get_credentials() vms = get_vms(cred) while True: selection = get_operation() if selection['operation'] == 'list': vms = get_vms(cred) print_vms(vms) elif selection['operation'] == 'power': vm_power = select_vm(vms) change_power_state(cred, vm_power['uuid']) elif selection['operation'] == 'delete': vm_delete = select_vm_delete(vms) if vm_delete['confirm']: delete_vm(cred, vm_delete['uuid']) elif selection['operation'] == 'clone': vm_clone = select_vm_clone(vms) clone_vm(cred, vm_clone['uuid'], int(vm_clone['count'])) elif selection['operation'] == 'exit': exit(0)
def boot(self, name, flavor, image, keyname): log("booting server " + name) server = self.nova.servers.create(name, image, flavor, key_name=keyname) return self.wait_for_vm(server)
def start(self): self.update_info() if self.points > 0: txt = "🤖 Hoho! I am back! You have %d points. Lets hack." % self.points log(txt, "blue") self.get_game_content()
def create_key(self, name): key_file = "/tmp/{0}.pem".format(name) log('saving key {0} to {1}'.format(name, key_file)) kpmgr = nc.keypairs.KeypairManager(self.nova) keypair = kpmgr.create(name) f = open(key_file, 'w') f.write(keypair.private_key) f.close() os.chmod(key_file, 0600) return key_file
def create_key(self, name): key_file = "/tmp/{0}.pem".format(name) log("saving key {0} to {1}".format(name, key_file)) kpmgr = nc.keypairs.KeypairManager(self.nova) keypair = kpmgr.create(name) f = open(key_file, "w") f.write(keypair.private_key) f.close() os.chmod(key_file, 0600) return key_file
def change_power_state(cred, uuid): api_result = http_request( 'PrismGateway/services/rest/v2.0/vms/{}'.format(uuid), cred) if api_result: vm = json.loads(api_result.content) if vm['power_state'].lower() == 'on': data = {'uuid': uuid, 'transition': 'OFF'} api_result = http_request( 'PrismGateway/services/rest/v2.0/vms/{}/set_power_state'. format(uuid), cred, method='POST', data=data) if api_result.status_code == 201: log('Powering off {} ...\n'.format(vm['name']), color='blue') else: log('Error changing the power state\n') else: data = {'uuid': uuid, 'transition': 'ON'} api_result = http_request( 'PrismGateway/services/rest/v2.0/vms/{}/set_power_state'. format(uuid), cred, method='POST', data=data) if api_result.status_code == 201: log('Powering on {} ...\n'.format(vm['name']), color='blue') else: log('Error changing the power state\n')
def update_info(self): soup = self.get_soup_from_page(self.base) try: self.xsrf_token = soup.find('input', {'name': 'xsrf_token'})['value'] self.points = int( soup.find('span', { 'class': 'nav__points' }).text) # storage points except TypeError: log("⛔ Cookie is not valid.", "red") sleep(10) exit()
def delete_vm(cred, uuid): api_result = http_request( 'PrismGateway/services/rest/v2.0/vms/{}'.format(uuid), cred, method='delete') if api_result: if api_result.status_code == 201: log('Deleting VM ...\n', color='blue') else: log('Error deleting the VM ...\n') else: log('Error deleting the VM ...\n')
def clone_vm(cred, uuid, count): api_result = http_request( 'PrismGateway/services/rest/v2.0/vms/{}'.format(uuid), cred) if api_result: vm = json.loads(api_result.content) for clone in range(count): clone_name = vm['name'] + ' - Clone {}'.format(clone + 1) data = {'uuid': uuid, 'spec_list': [{'name': clone_name}]} clone_result = http_request( 'PrismGateway/services/rest/v2.0/vms/{}/clone'.format(uuid), cred, method='POST', data=data) if clone_result.status_code == 201: log('Creating {}'.format(clone_name), color='blue') else: log('Error in creating clone\n') log('Cloning completed ...\n', color='blue')
def flavor(self, flavor_name): log("searching for flavor: " + flavor_name) flavors = [ f for f in self.nova.flavors.list() if f.name == flavor_name ] return flavors[0]
def image_by_regexp(self, reg): log("searching for image: " + reg) images = [i for i in self.nova.images.list() if re.match(reg, i.name)] if len(images) != 1: raise Exception("bad image regexp : " + reg + " : " + str(images)) return images[0]
def http_request(url, cred, headers={}, data=None, method='get', token=None, cookie=None): https = Config.HTTPS timeout = Config.HTTP_TIMEOUT verify_ssl = Config.VERIFY_SSL host = cred.get('pc_host') port = cred.get('pc_port') username = cred.get('username') password = cred.get('password') if https: url = 'https://{}:{}/{}'.format(host, port, url) else: url = 'http://{}:{}/{}'.format(host, port, url) if https and not verify_ssl: urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) if token: headers['Authorization'] = 'Bearer {}'.format(token) elif cookie: headers['Set-Cookie'] = '{}={}'.format(cookie.name, cookie.value) else: auth_str = '{}:{}'.format(username, password) base64_str = base64.encodebytes(auth_str.encode()).decode().replace( '\n', '') headers['Authorization'] = 'Basic {}'.format(base64_str) try: # https requests apply verify_ssl option if https: if method.lower() == 'get': response = requests.get(url, headers=headers, timeout=timeout, verify=verify_ssl) elif method.lower() == 'delete': response = requests.delete(url, headers=headers, timeout=timeout, verify=verify_ssl) elif method.lower() == 'post': response = requests.post(url, data=json.dumps(data), headers=headers, timeout=timeout, verify=verify_ssl) else: response = None else: # http request, so remove verify_ssl option else error is raised by requests lib if method.lower() == 'get': response = requests.get(url, headers=headers, timeout=timeout) elif method.lower() == 'post': response = requests.post(url, data=json.dumps(data), headers=headers, timeout=timeout) else: response = None except requests.ConnectTimeout: log('Connection time out while connecting to {}. Please check connectivity with backend' .format(url)) return False except requests.ConnectionError: log('Connection error while connecting to {}. Please check connectivity with backend.' .format(url)) return False except requests.HTTPError: log('Connection error while connecting to {}. Please check connectivity with backend.' .format(url)) return False except Exception as error: log('An unexpected error while connecting to {} - Exception: {}'. format(url, error.__class__.__name__)) return False return response
def get_game_content(self, page=1): n = page while True: txt = "⚙️ Retrieving games from %d page." % n log(txt, "magenta") filtered_url = self.filter_url[self.gifts_type] % n paginated_url = f"{self.base}/giveaways/{filtered_url}" soup = self.get_soup_from_page(paginated_url) game_list = soup.find_all('div', {'class': 'giveaway__row-inner-wrap'}) if not len(game_list): log("⛔ Page is empty. Please, select another type.", "red") sleep(10) exit() for item in game_list: if len(item.get('class', [])) == 2 and not self.pinned: continue if self.points == 0 or self.points < self.min_points: txt = f"🛋️ Sleeping to get 6 points. We have {self.points} points, but we need {self.min_points} to start." log(txt, "yellow") sleep(900) self.start() break game_cost = item.find_all( 'span', {'class': 'giveaway__heading__thin'})[-1] if game_cost: game_cost = game_cost.getText().replace('(', '').replace( ')', '').replace('P', '') else: continue game_name = item.find('a', { 'class': 'giveaway__heading__name' }).text if self.points - int(game_cost) < 0: txt = f"⛔ Not enough points to enter: {game_name}" log(txt, "red") continue elif self.points - int(game_cost) >= 0: game_id = item.find('a', {'class': 'giveaway__heading__name' })['href'].split('/')[2] res = self.entry_gift(game_id) if res: self.points -= int(game_cost) txt = f"🎉 One more game! Has just entered {game_name}" log(txt, "green") sleep(randint(3, 7)) n = n + 1 log("🛋️ List of games is ended. Waiting 2 mins to update...", "yellow") sleep(120) self.start()
def flavor(self, flavor_name): log("searching for flavor: " + flavor_name) flavors = [f for f in self.nova.flavors.list() if f.name == flavor_name] return flavors[0]