def grant_role2(args, role, user, project): '''grant role berdasarkan nama''' '''ex : python test.py grant_role2 roleirvan irvan irvan3''' ui.info_section(f'== Grant Role == \n') try: # mendapatkan id role dr nama cek = (f'{ks.roles.list(name=role)[0]}') baca = cek.strip().split(',') result = [i for i in baca if i.startswith(' id')] oke = result[0] id_role = oke.strip().strip('id=') # mendapatkan id user dr nama cek2 = (f'{ks.users.list(name=user)[0]}') baca2 = cek2.strip().split(',') result2 = [i for i in baca2 if i.startswith(' id')] oke2 = result2[0] id_user = oke2.strip().strip('id=') # mendapaktan id project dr nama cek3 = (f'{ks.projects.list(name=project)[0]}') baca3 = cek3.strip().split(',') result3 = [i for i in baca3 if i.startswith(' id')] oke3 = result3[0] id_project = oke3.strip().strip('id=') ex = ks.roles.grant(role=id_role, user=id_user, system=None, project=id_project) ui.info_3(ex) ui.info_3('\n Done ', ui.check) except Exception as e: '''jika tidak ada nama''' ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
def fetch_tweets(): """This will start collection and will store them in the database. //DONE: Ask the user to change filter keyword value. //TODO bug: counter resets on disconnection so it starts gathering x tweets on top of whatever it gathered before. """ try: trump = change_filter() # A variable named trump myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener) myStream.filter(track=[trump]) myStream.disconnect() except sqlite3.InterfaceError as e: ui.info_3(e) ui.error("Connection timeout... Reconnecting...") myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener) myStream.filter(track=[trump]) myStream.disconnect() except urlib3.exceptions.ProtocolError as e: ui.info_3(e) ui.error("Connection broken... Reconnecting...") myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener) myStream.filter(track=[trump]) myStream.disconnect()
def grant_role(args, role, user, project): '''tanpa di grant gk bisa login, grant ke member saja''' try: ex = ks.roles.grant(role=role, user=user, system=None, project=project) ui.info_3(ex) ui.info_3('\n Done ', ui.check) except Exception as e: '''jika tidak ada nama''' ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
def ploting(tweets_db=TWEETS_DB, csv_file=CSV_FILE): table_name = MyStreamListener.table_name plot_question = ui.ask_yes_no("Plot?", default=True) if plot_question: ui.info(ui.green, "Populating csv file with {}".format(table_name)) q_four.db_into_csv(TWEETS_DB, CSV_FILE, table_name) ui.info_3("Ploting...") q_four.frecuency() q_four.senti() else: ui.info(ui.turquoise, "Program Finished") exit()
def delete_project(args, name): '''delete project by name''' try: '''memcoba''' cek = (f'{ks.projects.list(name=name)[0]}') baca = cek.strip().split(',') result = [i for i in baca if i.startswith(' id')] oke = result[0] id_project = oke.strip().strip('id=') ks.projects.delete(id_project) ui.info_3(f'Delete {id_project} success', ui.check) except Exception as e: '''jika tidak ada nama''' ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
def update_project(args, name, nameedit, description=None): '''update projects''' if description is None: try: cek = (f'{ks.projects.list(name=name)[0]}') baca = cek.strip().split(',') result = [i for i in baca if i.startswith(' id')] oke = result[0] id_project = oke.strip().strip('id=') update = ks.projects.update( project=id_project, name=nameedit) ui.info_3(update, '\n') ui.info_3('\n Done ', ui.check) except Exception as e: '''jika tidak ada nama''' ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e) else: try: cek = (f'{ks.projects.list(name=name)[0]}') baca = cek.strip().split(',') result = [i for i in baca if i.startswith(' id')] oke = result[0] id_project = oke.strip().strip('id=') update = ks.projects.update( project=id_project, name=nameedit, description=description) ui.info_3(update, '\n') ui.info_3('\n Done ', ui.check) except Exception as e: '''jika tidak ada nama''' ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
def instance(args, id=None): r = os.environ.get("OS_TOKEN") header = {'X-Auth-Token': r} if id is None: ui.info_section('== List instance ==\n') instance = requests.get( "http://rocky-controller.jcamp.net:8774/v2.1/servers", headers=header) readjson = json.loads(instance.content) coba = json.dumps(readjson, sort_keys=True, indent=2) print(coba) elif id == "create": ui.info_section('== Create Instance == \n') url = "http://rocky-controller.jcamp.net:8774/v2.1/servers" data = """ { "server": { "name": "percobaan", "imageRef": "82189ef1-2c20-475c-9d40-325eb567df56", "flavorRef": "afc68ef6-1985-4d59-ac63-a6f2c4405756", "availability_zone": "nova", "key_name": "Laptop Hp", "OS-DCF:diskConfig": "AUTO", "networks": [{ "uuid": "4b73b027-0231-42e8-9253-153f342119d9" }], "security_groups": [{ "name": "default" }] } } """ ui.info('loading', ui.ellipsis) r = requests.post(url, data, headers=header) readjson = json.loads(r.content) coba = json.dumps(readjson, sort_keys=True, indent=2) print(coba) ui.info_3('\n Done ', ui.check) else: try: ui.info_section(ui.bold, '== Detail Image == \n') images = requests.get( f"http://rocky-controller.jcamp.net:8774/v2.1/servers/{id}", headers=header) readjson = json.loads(images.content) showjson = json.dumps(readjson, sort_keys=True, indent=2) print(showjson) except ValueError as e: ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e) ui.info("Id Image tidak ada")
def delete_user(args, user): ''' Perintah untuk menghapus user create_project(args, user) Args: args (str): argument function create_project. user : id user yg ingin dihapus contoh: python test.py delete_user 83cadda8794743e7923821a38fea2683 ''' try: delete = ks.users.delete(user=user) ui.info_3(delete, '\n') ui.info_3('\n Done ', ui.check) except Exception as e: ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
def images(args, id=None): r = os.environ.get("OS_TOKEN") # print(os.environ.get("OS_TOKEN")) header = { 'X-Auth-Token': r, "Content-Type": "application/json" } if id is None: print("== List Image == \n") elif id == "create": print("== create Image == \n") url = "http://rocky-controller.jcamp.net:8774/v2.1/servers" data = """ { "server": { "name": "cobabuatlg", "imageRef": "82189ef1-2c20-475c-9d40-325eb567df56", "flavorRef": "afc68ef6-1985-4d59-ac63-a6f2c4405756", "availability_zone": "nova", "key_name": "Laptop Hp", "OS-DCF:diskConfig": "AUTO", "networks": [{ "uuid": "4b73b027-0231-42e8-9253-153f342119d9" }], "security_groups": [{ "name": "default" }] } } """ ui.info("loading .. \n") requests.post(url, data, headers=header) ui.info_3("::done::") else: try: print("== Detail Image == \n") images = requests.get( f"http://rocky-controller.jcamp.net:9292/v2/images/{id}", headers=header) readjson = json.loads(images.content) showjson = json.dumps(readjson, sort_keys=True, indent=2) print(showjson) except ValueError as e: ui.info(ui.red, 'Error: ', ui.reset, e) ui.info("Id Image tidak ada")
def delete_network(args, network_id): '''Hapus network''' ui.info_section(f'== Delete Network == \n') auth = identity.Password(auth_url=auth_url, username=username, password=password, project_name=project_name, project_domain_name=project_domain_name, user_domain_name=user_domain_name) sess = session.Session(auth=auth) neutron = nwclient.Client(session=sess) # neutron.delete_network(network_id) try: '''memcoba''' neutron.delete_network(network_id) ui.info_3(f'Delete {network_id} success', ui.check) except Exception as e: '''jika gagal''' ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
def change_filter(): """Changes the search filter for myStream.filter(track=[trump]) :param: :return trump: New keyword or DEFAULT keyword 'trump'""" trump = 'trump' # A variable named trump. ui.info_1(ui.yellow, "SEARCH:", ui.blue, ui.standout, "'trump'") ans_filter = ui.ask_yes_no("Change search keyword? [Ctrl-C Quits] >>>", default=False) if ans_filter == False: return trump else: ui.info_1(ui.red, "Really change?") ans_really = ui.ask_yes_no("[ENTER] for No >>>", default=False) if ans_really == False: return trump else: trump = ui.ask_string("Enter new search keyword") ui.info_3("Starting search for new keyword:", ui.blue, trump) return trump
def create_project(args, name, domain, description): ''' Perintah untuk membuat project create_project name domain description Args: args (str): argument function create_project. name (str): name project. domain : id domain untuk project description: deskripsi project contoh: python test.py create_project irvan3 default coba... ''' ui.info_section(f'== create project {name}== \n') try: enabled = True create = ks.projects.create(name=name, domain=domain, description=description, enabled=enabled) ui.info_3(create, '\n') ui.info_3('\n Done ', ui.check) except Exception as e: '''jika tidak ada nama''' ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
def revoke_role(args, role, user, project): '''mencabut role''' try: '''revoke roles''' cek = (f'{ks.roles.list(name=role)[0]}') baca = cek.strip().split(',') result = [i for i in baca if i.startswith(' id')] oke = result[0] id_roles = oke.strip().strip('id=') cek1 = (f'{ks.projects.list(name=project)[0]}') baca1 = cek1.strip().split(',') result1 = [i for i in baca1 if i.startswith(' id')] oke1 = result1[0] id_project = oke1.strip().strip('id=') cek2 = (f'{ks.users.list(name=user)[0]}') baca2 = cek2.strip().split(',') result2 = [i for i in baca2 if i.startswith(' id')] oke2 = result2[0] id_user = oke2.strip().strip('id=') cabut = ks.roles.revoke( role=id_roles, user=id_user, project=id_project) ui.info_3('revoke role success', ui.check) ui.info_3(cabut, '\n') ui.info_3('Done ', ui.check) except Exception as e: '''jika tidak ada nama''' ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
def create_network(args, name, subnetname, cidr): '''buat network''' '''namanetwork namasubnet networkaddress''' # network_name = 'int_network1' ui.info_section(f'== Create Network {name}== \n') auth = identity.Password(auth_url=auth_url, username=username, password=password, project_name=project_name, project_domain_name=project_domain_name, user_domain_name=user_domain_name) sess = session.Session(auth=auth) neutron = nwclient.Client(session=sess) try: body_sample = {'network': {'name': name, 'admin_state_up': True}} netw = neutron.create_network(body=body_sample) net_dict = netw['network'] network_id = net_dict['id'] ui.info_3('Network %s created' % network_id, ui.check) body_create_subnet = {'subnets': [{'cidr': cidr, 'name': subnetname, 'ip_version': 4, 'network_id': network_id}]} subnet = neutron.create_subnet(body=body_create_subnet) ui.info_3('Created subnet %s' % subnet, ui.check) finally: ui.info_3("Execution completed", ui.check)
def delete_users(args, *users): '''delete beberapa user by name''' ui.info_section('== Delete Users== \n') for item in users: try: ui.info_3(' -----') cek = (f'{ks.users.list(name=item)[0]}') baca = cek.strip().split(',') result = [i for i in baca if i.startswith(' id')] oke = result[0] id_user = oke.strip().strip('id=') ui.info_3(f'Deleting Users {id_user} \n', ui.ellipsis) delete = ks.users.delete(user=id_user) ui.info_3(delete, '\n') ui.info_3('Delete Succes', ui.check) except Exception as e: ui.info(ui.red, ui.bold, 'Error: nama user gk ada', ui.reset, e) continue
def create_instance(args, name, flavors, image, network, securitygroups, keypairname): '''Membuat Instance''' try: ui.info_section(f'== Create Instance == \n') loader = loading.get_plugin_loader('password') auth = loader.load_from_options( auth_url=auth_url, username=username, password=password, project_name=project_name, project_domain_name=project_domain_name, user_domain_name=user_domain_name ) sess = session.Session(auth=auth) nova_client = nvclient.Client('2', session=sess) image = nova_client.glance.find_image(image) flavor = nova_client.flavors.find(name=flavors) net = nova_client.neutron.find_network(name=network) nics = [{'net-id': net.id}] network = nwclient.Client(session=sess) sg = network.list_security_groups(name=securitygroups) id_sg = sg['security_groups'][0]['id'] id_sg1 = print(id_sg) instance = nova_client.servers.create(name=name, image=image, flavor=flavor, key_name=keypairname, security_groups=id_sg1, nics=nics) # block_dev_mapping = {'vda':'uuid of the volume you want to use'} # https://ask.openstack.org/en/question/54104/create-an-instance-from-volume-in-openstach-with-python-novaclient/ # https://stackoverflow.com/questions/27048292/create-an-instance-from-volume-in-openstach-with-python-novaclient/27136929#27136929 # instance = nova.servers.create(name="python-test3", image='', block_device_mapping=block_dev_mapping, # flavor = flavor, key_name = "my-keypair", nics = nics) ui.info_3("Processing", ui.ellipsis) time.sleep(5) ui.info_3("Create Instance Success", ui.check) ui.info_3("List Instance : ") print(nova_client.servers.list()) finally: ui.info_3("Execution Completed", ui.check)
def create_floatingip(args, ext_network, internal_ip): '''Membuat floating IP''' try: ui.info_section(f'== Create Floating Ip == \n') auth = identity.Password(auth_url=auth_url, username=username, password=password, project_name=project_name, project_domain_name=project_domain_name, user_domain_name=user_domain_name) sess = session.Session(auth=auth) neutron = nwclient.Client(session=sess) # mendapatkan id ext_network berdasarkan nama(external network) net = neutron.list_networks(name=ext_network) id_network = net['networks'][0]['id'] # mendapatkan port id berdasarkan ip network = neutron.list_ports()['ports'] tes = [ elem['id'] for elem in network if(elem['fixed_ips'][0]['ip_address'] == internal_ip) ] port_id = tes[0] request = { "floatingip": { # ext network "floating_network_id": id_network, "port_id": port_id, "fixed_ip_address": internal_ip, } } floating_ip = neutron.create_floatingip(request) ui.info_3("Processing", floating_ip, ui.ellipsis) time.sleep(5) ui.info_3("Create Floating Ip Success", ui.check) finally: '''akhirnya''' ui.info_3("Execution Completed", ui.check)
def create_route(args, name, ext_network, namesubnet): '''Membuat Routes''' '''Cmd : python test.py create_route cobaroute2 ext-net subnet3 ''' try: ui.info_section(f'== Create Routes == \n') auth = identity.Password(auth_url=auth_url, username=username, password=password, project_name=project_name, project_domain_name=project_domain_name, user_domain_name=user_domain_name) sess = session.Session(auth=auth) neutron = nwclient.Client(session=sess) # mendapatkan id extnetwork net = neutron.list_networks(name=ext_network) id_network = net['networks'][0]['id'] # mendapatkan id subnet subnet = neutron.list_subnets(name=namesubnet) subnet_id = subnet['subnets'][0]['id'] neutron.format = 'json' request = {'router': {'name': name, 'external_gateway_info': {"network_id": id_network}, 'admin_state_up': True}} router = neutron.create_router(request) router_id = router['router']['id'] # for example: '72cf1682-60a8-4890-b0ed-6bad7d9f5466' router = neutron.show_router(router_id) ui.info_3(router, ui.check) body = {'subnet_id': subnet_id} response = neutron.add_interface_router( router=router_id, body=body) ui.info_3(response, ui.check) finally: ui.info_3("Execution completed", ui.check)
def create_user(args, name, domain, project, password, email=None, description=None): ''' Perintah untuk membuat user create_user name domain project password email description Args: args (str): argument function create_user. name (str): name project. domain : id domain untuk user project : id project untuk user password : password untuk user yg dibuat email : email (optional) description: deskripsi user (optional) contoh: python test.py create_user irvan8 default 6bd9cebb746c420783039ce7606f8aa1 M0nalisa [email protected] fojijbgigtr ''' ui.info_section(f'== Create User == \n') if email is None and description is None: '''jika diisi hanya sampai password''' try: enabled = True create = ks.users.create(name=name, domain=domain, project=project, password=password, enabled=enabled) ui.info_3(create, '\n') ui.info_3('\n Done ', ui.check) except Exception as e: ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e) elif description is None: '''description kosong''' try: enabled = True create = ks.users.create(name=name, domain=domain, project=project, password=password, email=email, enabled=enabled) ui.info_3(create, '\n') ui.info_3('\n Done ', ui.check) except Exception as e: ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e) else: try: enabled = True # cek = (f'{ks.projects.list(name=name)[0]}') # baca = cek.strip().split(',') # result = [i for i in baca if i.startswith(' id')] # oke = result[0] # id_project = oke.strip().strip('id=') create = ks.users.create(name=name, domain=domain, project=project, password=password, email=email, description=description, enabled=enabled) ui.info_3(create, '\n') ui.info_3('\n Done ', ui.check) except Exception as e: ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)