Exemplo n.º 1
0
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)
Exemplo n.º 2
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)
Exemplo n.º 3
0
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)
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
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)
Exemplo n.º 6
0
 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")
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
    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()
Exemplo n.º 10
0
 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
Exemplo n.º 11
0
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
Exemplo n.º 12
0
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
Exemplo n.º 13
0
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.")
Exemplo n.º 14
0
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)
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
def UpdateApiKey(NewKey):
	global vultr
	vultr = Vultr(NewKey)
	with open("api_key.txt", "w") as f:
		f.write(NewKey)
		f.close()
Exemplo n.º 17
0
 def setUp(self):
     self.vultr = Vultr('')
Exemplo n.º 18
0
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)
Exemplo n.º 19
0
 def get_isp_obj(self, **kwargs: dict):
     return Vultr(self.api_token)
Exemplo n.º 20
0
FWD_TO_EMAIL = "YOUR_EMAIL"

# NAMESILO DETAILS
NAMESILO_API_KEY = "YOUR_API_KEY"

# VULTR DETAILS
VULTR_API_KEY = "YOUR_API_KEY"
VULTR_REGIONS = {'New Jersey, NY': 1, 'Chicago, IL': 2, 'London, GB': 8}
# $5 1 CPU 1024MB Mem 1000GB Bw
VULTR_PLAN_ID = 201
# Application
VULTR_OS_ID = 186
# Wordpress (Ubuntu 16.04 x64)
VULTR_APP_ID = 2

vultr = Vultr(VULTR_API_KEY)
namesilo = NameSilo(NAMESILO_API_KEY, live=True)


def available_plans():
    """This isn't right, it's missing a couple plans."""
    try:
        return vultr.plans.list()
    except VultrError as ex:
        logging.error('VultrError: %s', ex)


def create_instance(dcid, vpsplanid, osid, params):
    # create(self, dcid, vpsplanid, osid, params=None):
    try:
        response = vultr.server.create(dcid, vpsplanid, osid, params)
Exemplo n.º 21
0
def startupscript_destroy(ctx, scriptid):
    """
    Remove a startup script
    """
    vultr = Vultr(get_key())
    return vultr.startupscript.destroy(scriptid)
Exemplo n.º 22
0
def stop():
    vultr = Vultr(API_KEY)
    vultr.server.halt(SUB_ID)
Exemplo n.º 23
0
def start():
    vultr = Vultr(API_KEY)
    vultr.server.start(SUB_ID)
Exemplo n.º 24
0
def destroy():
    vultr = Vultr(API_KEY)
    vultr.server.destroy(SUB_ID)
Exemplo n.º 25
0
 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}
Exemplo n.º 26
0
def snapshot_list(ctx, snapshotid=None, criteria=''):
    """
    List all snapshots on the current account
    """
    params = param_dict(snapshotid=snapshotid)
    return query(ctx, lambda x: Vultr(x).snapshot.list(params), criteria)
Exemplo n.º 27
0
 def setUpClass(cls):
     cls.VULTR_KEY = os.environ.get('VULTR_KEY')
     cls.vultr = Vultr(cls.VULTR_KEY)
     cls.server_list = {}
Exemplo n.º 28
0
def sshkey_list(ctx, criteria=''):
    """
    List all the SSH keys on the current account
    """
    return query(ctx, lambda x: Vultr(x).sshkey.list(), criteria)
#!/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)
Exemplo n.º 30
0
def os_list(ctx, criteria=''):
    """
    Retrieve a list of available operating systems
    """
    return query(ctx, lambda x: Vultr(x).os.list(), criteria)