class AuthenticatedTests(unittest.TestCase): def setUp(self): self.VULTR_KEY = os.environ.get('VULTR_KEY') if self.VULTR_KEY is None: warnings.warn('The VULTR_KEY environment variable is not ' + 'set. AuthenticatedTests will be bypassed.', UserWarning) else: self.vultr = Vultr(self.VULTR_KEY) def test_get_api_key(self): if self.VULTR_KEY is None: return response = self.vultr.iso_list() def test_post_api_key(self): if self.VULTR_KEY is None: return try: response = self.vultr.server_label_set('', '') except VultrError as e: msg = str(e) self.assertEqual(msg, "Request failed. Check the response body" + " for a more detailed description. Body:" + " \nInvalid server. Check SUBID value and" + " ensure your API key matches the server's" + " account")
class AuthenticatedTests(unittest.TestCase): def setUp(self): self.VULTR_KEY = os.environ.get('VULTR_KEY') if self.VULTR_KEY is None: warnings.warn( 'The VULTR_KEY environment variable is not ' + 'set. AuthenticatedTests will be bypassed.', UserWarning) else: self.vultr = Vultr(self.VULTR_KEY) def test_get_api_key(self): if self.VULTR_KEY is None: return response = self.vultr.iso_list() def test_post_api_key(self): if self.VULTR_KEY is None: return try: response = self.vultr.server_label_set('', '') except VultrError as e: msg = str(e) self.assertEqual( msg, "Request failed. Check the response body" + " for a more detailed description. Body:" + " \nInvalid server. Check SUBID value and" + " ensure your API key matches the server's" + " account")
def setUp(self): self.VULTR_KEY = os.environ.get('VULTR_KEY') if self.VULTR_KEY is None: warnings.warn( 'The VULTR_KEY environment variable is not ' + 'set. AuthenticatedTests will be bypassed.', UserWarning) else: self.vultr = Vultr(self.VULTR_KEY)
def destroy(self, wipe=False): self.log("destroying instance {}".format(self.subid)) vultr = Vultr(self.get_api_key()) try: vultr.server_destroy(self.subid) except VultrError: self.log( "An error occurred destroying instance. Assuming it's been destroyed already." ) self.public_ipv4 = None self.subid = None
class UnauthenticateTests(unittest.TestCase): def setUp(self): self.vultr = Vultr('') def test_plans_list(self): response = self.vultr.plans_list() def test_regions_list(self): response = self.vultr.regions_list() def test_os_list(self): response = self.vultr.os_list() def test_app_list(self): response = self.vultr.app_list()
def __init__(self, api_key): """Initialize the Vultr connection.""" from vultr import Vultr as VultrAPI self._api_key = api_key self.data = None self.api = VultrAPI(self._api_key)
def plans_list(ctx, criteria='', _type=None): """ Retrieve a list of all active plans. Plans that are no longer available will not be shown. """ params = param_dict(_type=_type) return query(ctx, lambda x: Vultr(x).plans.list(params), criteria)
def main(): global api_key global vultr vultr = Vultr(api_key) os.system('clear') while True: i=int(raw_input('Main Menu\n1) Write IPs to txt\n2) Destroy All Servers\n3) Change API Key\n4) Current API Key\n5) Create Servers\n6) Exit\n')) os.system('clear') if i == 1: ListServerIps() elif i == 2: i = raw_input('Are you sure you want to destroy all servers?(Y/n)') if i == 'Y': DestroyAllServers() elif i == 'n': pass else: print "Y/n only" elif i == 3: ChangeApiKey() elif i == 4: print vultr.api_key elif i == 5: CreateServers() elif i == 6: sys.exit(0)
def regions_list(ctx, criteria=''): """ Retrieve a list of all active regions Note that just because a region is listed here, does not mean that there is room for new servers """ return query(ctx, lambda x: Vultr(x).regions.list(), criteria)
def server_destroy(ctx, subid): """ Destroy (delete) a virtual machine. All data will be permanently lost, and the IP address will be released. There is no going back from this call """ vultr = Vultr(get_key()) return vultr.server.destroy(subid)
def startupscript_list(ctx, criteria=''): """ List all startup scripts on the current account. Scripts of type "boot" are executed by the server's operating system on the first boot. Scripts of type "pxe" are executed by iPXE when the server itself starts up """ return query(ctx, lambda x: Vultr(x).startupscript.list(), criteria)
def __init__(self): ''' Instantiate all required variables ''' self.dataTable = PrettyTable() self.dataTable.field_names = ['Instance Name', 'Instance IP', 'Status'] try: self.vultr = Vultr(get_env('VULTR_TOKEN')) except: print("Problem during vultr object initialization")
def setUp(self): self.VULTR_KEY = os.environ.get('VULTR_KEY') if self.VULTR_KEY is None: warnings.warn('The VULTR_KEY environment variable is not ' + 'set. AuthenticatedTests will be bypassed.', UserWarning) else: self.vultr = Vultr(self.VULTR_KEY)
def startupscript_update(ctx, scriptid, name='', script=''): """ Update an existing startup script """ vultr = Vultr(get_key()) if os.path.exists(script): script = _read_script(script) params = param_dict(name=name, script=script) return vultr.startupscript.update(scriptid, params)
def startupscript_create(ctx, name, script, _type=None): """ Create a startup script """ vultr = Vultr(get_key()) if os.path.exists(script): script = _read_script(script) params = param_dict(_type=_type) response = vultr.startupscript.create(name, script, params) if ctx.config.run.echo: display_yaml(response) return response
class Vultr: """Handle all communication with the Vultr API.""" def __init__(self, api_key): """Initialize the Vultr connection.""" self._api_key = api_key self.data = None self.api = VultrAPI(self._api_key) @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Use the data from Vultr API.""" self.data = self.api.server_list() def _force_update(self): """Use the data from Vultr API.""" self.data = self.api.server_list() def halt(self, subscription): """Halt a subscription (hard power off).""" self.api.server_halt(subscription) self._force_update() def start(self, subscription): """Start a subscription.""" self.api.server_start(subscription) self._force_update()
class Vultr(object): """Handle all communication with the Vultr API.""" def __init__(self, api_key): """Initialize the Vultr connection.""" from vultr import Vultr as VultrAPI self._api_key = api_key self.data = None self.api = VultrAPI(self._api_key) @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Use the data from Vultr API.""" self.data = self.api.server_list() def _force_update(self): """Use the data from Vultr API.""" self.data = self.api.server_list() def halt(self, subscription): """Halt a subscription (hard power off).""" self.api.server_halt(subscription) self._force_update() def start(self, subscription): """Start a subscription.""" self.api.server_start(subscription) self._force_update()
def create(self, defn, check, allow_reboot, allow_recreate): self.set_common_state(defn) if self.subid is not None: return self.log_start("creating instance ...") self.log("dcid: " + str(defn.dcid)) self.log("osid: " + str(defn.osid)) self.log("vpsplanid: " + str(defn.vpsplanid)) self.log("snapshotid: " + str(defn.snapshotid)) self.log("label: " + str(defn.label)) vultr = Vultr(self.get_api_key()) snapshots = vultr.snapshot_list() if defn.snapshotid not in snapshots: raise Exception( "Unexpected Error: snapshot {} does not exist".format( defn.snapshotid)) server_create_output = vultr.server_create( dcid=defn.dcid, osid=defn.osid, vpsplanid=defn.vpsplanid, snapshotid=defn.snapshotid, enable_ipv6='yes', enable_private_network='yes', label=defn.label) subid = server_create_output['SUBID'] self.log("instance id: " + subid) server_info = vultr.server_list()[subid] while server_info[ 'status'] == 'pending' or server_info['server_state'] != 'ok': server_info = vultr.server_list()[subid] time.sleep(1) self.log_continue("[status: {} state: {}] ".format( server_info['status'], server_info['server_state'])) if server_info['status'] == 'active' and server_info[ 'server_state'] == 'ok': # vultr sets ok before locked when restoring snapshot. Need to make sure we're really ready. time.sleep(10) server_info = vultr.server_list()[subid] if server_info['status'] != 'active' or server_info[ 'server_state'] != 'ok': raise Exception("unexpected status: {}/{}".format( server_info['status'], server_info['server_state'])) self.subid = subid self.label = server_info['label'] self.log_start("generating new SSH keypair... ") key_name = "NixOps client key for {0}".format(self.subid) self._ssh_private_key, self._ssh_public_key = \ nixops.util.create_key_pair(key_name=key_name) self.public_ipv4 = server_info['main_ip'] self.log_end("{}".format(self.public_ipv4)) self.default_gateway = server_info['gateway_v4'] self.netmask = server_info['netmask_v4'] self.wait_for_ssh()
def server_create(ctx, dcid, vpsplanid, osid, ipxe_chain_url=None, isoid=None, scriptid=None, snapshotid=None, enable_ipv6=None, enable_private_network=None, label=None, sshkeyid=None, auto_backups=None, appid=None, userdata=None, notify_activate=None, ddos_protection=None, reserved_ip_v4=None, hostname=None, tag=None, firewallgroupid=None): """ Create a new virtual machine You will start being billed for this immediately The response only contains the SUBID for the new machine """ params = param_dict( ipxe_chain_url=ipxe_chain_url, scriptid=scriptid, snapshotid=snapshotid, enable_ipv6=enable_ipv6, enable_private_network=enable_private_network, label=label, sshkeyid=sshkeyid, auto_backups=auto_backups, appid=appid, userdata=userdata, notify_activate=notify_activate, ddos_protection=ddos_protection, reserved_ip_v4=reserved_ip_v4, hostname=hostname, tag=tag, firewallgroupid=firewallgroupid, ) vultr = Vultr(get_key()) response = vultr.server.create(dcid, vpsplanid, osid, params or None) if ctx.config.run.echo: display_yaml(response) return response
def servers_running(): '''Shows running servers''' vultr = Vultr(API_KEY) try: serverList = vultr.server.list() #logging.info('Listing servers:\n%s', dumps( #serverList, indent=2 #)) except VultrError as ex: logging.error('VultrError: %s', ex) for serverID in serverList: if serverList[serverID]['power_status'] == 'running': logging.info(serverList[serverID]['label'] + " is up and running.")
def server_list(ctx, subid=None, tag=None, label=None, main_ip=None, criteria=''): """ List all active or pending virtual machines on the current account. The "status" field represents the status of the subscription and will be one of: pending | active | suspended | closed. If the status is "active", you can check "power_status" to determine if the VPS is powered on or not. When status is "active", you may also use "server_state" for a more detailed status of: none | locked | installingbooting | isomounting | ok. The API does not provide any way to determine if the initial installation has completed or not. The "v6_network", "v6_main_ip", and "v6_network_size" fields are deprecated in favor of "v6_networks". """ params = param_dict(tag=tag, label=label, main_ip=main_ip) return query(ctx, lambda x: Vultr(x).server.list(subid=subid, params=params), criteria)
def dump_info(): '''Shows various details about the account & servers''' vultr = Vultr(API_KEY) try: logging.info('Listing account info:\n%s', dumps(vultr.account.info(), indent=2)) logging.info('Listing apps:\n%s', dumps(vultr.app.list(), indent=2)) logging.info('Listing backups:\n%s', dumps(vultr.backup.list(), indent=2)) logging.info('Listing DNS:\n%s', dumps(vultr.dns.list(), indent=2)) logging.info('Listing ISOs:\n%s', dumps(vultr.iso.list(), indent=2)) logging.info('Listing OSs:\n%s', dumps(vultr.os.list(), indent=2)) logging.info('Listing plans:\n%s', dumps(vultr.plans.list(), indent=2)) logging.info('Listing regions:\n%s', dumps(vultr.regions.list(), indent=2)) logging.info('Listing servers:\n%s', dumps(vultr.server.list(), indent=2)) logging.info('Listing snapshots:\n%s', dumps(vultr.snapshot.list(), indent=2)) logging.info('Listing SSH keys:\n%s', dumps(vultr.sshkey.list(), indent=2)) logging.info('Listing startup scripts:\n%s', dumps(vultr.startupscript.list(), indent=2)) except VultrError as ex: logging.error('VultrError: %s', ex)
def __init__(self, api_key): """Initialize the Vultr connection.""" self._api_key = api_key self.data = None self.api = VultrAPI(self._api_key)
def start(): vultr = Vultr(API_KEY) vultr.server.start(SUB_ID)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= # Author : Will Grant # ============================================================================= import json from vultr import Vultr api_key = '' vultr = Vultr(api_key) plans_json = vultr.dns.list() with open('data.json', 'w', encoding='utf-8') as f: json.dump(plans_json, f, ensure_ascii=False, sort_keys=True, indent=2, skipkeys=True, separators=(',\n', ':')) with open('data.json', 'r') as f: data = json.load(f)
def __init__(self): super().__init__(__file__) self.type = "cleaner" self.taskLog = [] self.tmpSnapshotID = "" self.targetVPS = None self.queryInterval = int(self.config.get('cleaner', 'queryInterval')) self.createMinTime = int(self.config.get('cleaner', 'createMinTime')) self.destroyWaitTime = int( self.config.get('cleaner', 'destroyWaitTime')) self.timeZone = int(self.config.get('cleaner', 'timeZone')) self.sshPassword = self.config.get('cleaner', 'sshPassword') self.oldVPSList = [] self.oldIPv4List = [] self.vultrDestroyCoolTime = int( self.config.get('cleaner', 'vultrDestroyCoolTime')) self.destroyPool = ThreadPool(processes=self.maxThreads * 4) self.destroyResults = [] self.VULTR512MPLANID = '200' self.VULTR1024MPLANID = '201' self.CONOHA1024PLANID = '7eea7469-0d85-4f82-8050-6ae742394681' self.lastException = None self.taskState = [ 'Pending', 'Destroying', 'Creating', 'Watching', 'Shiny☆', 'Failing', 'Snapshotting', 'Destroying', 'Updating DNS', 'Updating node info', 'Desnapshotting' ] self.taskStateID = 0 self.birthTime = int(time.time()) self.attempts = 0 self.taskStateEmoji = { 'working': '🔶', 'success': '🔵', 'fail': '🔴' } # Init Vultr api instance self.vultrApikey = self.config.get('cleaner', 'vultrApikey') self.vultr = Vultr(self.vultrApikey) # Init ConohaConfig instance self.conoha_conf = ConohaConfig( fromDict={ 'api': { 'user': self.config.get('cleaner', 'conohaUser'), 'passwd': self.config.get('cleaner', 'conohaPasswd'), 'tenant': self.config.get('cleaner', 'conohaTenant') } }) self.conoha_token = None self.conoha_vmlist = None # Init dnsimple api instance self.dnsimpleUsername = self.config.get('cleaner', 'dnsimpleUsername') self.dnsimplePassword = self.config.get('cleaner', 'dnsimplePassword') self.dns = DNSimple(email=self.dnsimpleUsername, password=self.dnsimplePassword) # Function dic for different VPS providers self.supportedVPSProviderList = ['Vultr', 'Conoha'] self.supportedDNSProviderList = ['DNSimple'] self.init_provider_api = { 'Vultr': self.init_provider_api_vultr, 'Conoha': self.init_provider_api_conoha } self.create_tmp_snapshot = { 'Vultr': self.create_tmp_snapshot_vultr, 'Conoha': self.create_tmp_snapshot_conoha } self.destroy_tmp_snapshot = { 'Vultr': self.destroy_tmp_snapshot_vultr, 'Conoha': self.destroy_tmp_snapshot_conoha } self.get_server_info = { 'Vultr': self.get_server_info_vultr, 'Conoha': self.get_server_info_conoha } self.destroy_and_create = { 'Vultr': self.destroy_and_create_vultr, 'Conoha': self.destroy_and_create_conoha } self.get_server_ip = { 'Vultr': self.get_server_ip_vultr, 'Conoha': self.get_server_ip_conoha } self.update_dns = {'DNSimple': self.update_dns_dnsimple}
def destroy(): vultr = Vultr(API_KEY) vultr.server.destroy(SUB_ID)
def startupscript_destroy(ctx, scriptid): """ Remove a startup script """ vultr = Vultr(get_key()) return vultr.startupscript.destroy(scriptid)
def UpdateApiKey(NewKey): global vultr vultr = Vultr(NewKey) with open("api_key.txt", "w") as f: f.write(NewKey) f.close()
def setUpClass(cls): cls.VULTR_KEY = os.environ.get('VULTR_KEY') cls.vultr = Vultr(cls.VULTR_KEY) cls.server_list = {}
def get_isp_obj(self, **kwargs: dict): return Vultr(self.api_token)
def setUp(self): self.vultr = Vultr('')
def app_list(ctx, criteria=''): """ Retrieve a list of available applications These refer to applications that can be launched when creating a Vultr VPS """ return query(ctx, lambda x: Vultr(x).app.list(), criteria)