コード例 #1
0
def reboot_server(server_id=LINODE_ID):
    """
    Using the Linode Python Library, reboot the specified server(s)

    Args:
        servers: list of ints - The integer ID numbers for servers to reboot

    Returns:
        None

    Raises:
        ValueError -- if supplied server IDs cannot be changed to integers
     """

    # Make sure server ID is an integer, or is at least convertible to one
    try:
        server_id = int(server_id)
    except ValueError as e:
        raise e

    # Connect to Linode
    client = LinodeClient(LINODE_TOKEN)

    # Harness my particular server
    my_server = client.load(Instance, server_id)

    # Reboot server
    my_server.reboot()
コード例 #2
0
def reboot_server():
    client = LinodeClient(LINODE_TOKEN)

    # Print out all of the instances on the linode server
    # for my_linode in client.linode_api4.instances():
    #     print(f"{linode.label}: {linode.id}")
    
    my_server = client.load(Instance, 376715)
    my_server.reboot()
コード例 #3
0
ファイル: create_linode.py プロジェクト: frookazoid/LINODE
 def __init__(self):
     self.API_KEY = API_KEY
     self.client = LinodeClient(API_KEY)
     self.region = None
     self.ltype = None
     self.image = "linode/ubuntu16.04lts"
     self.stackscript = 68166
     self.count = raw_input('How many proxies would you like to make?: ')
     self.set_region()
     self.set_type()
コード例 #4
0
ファイル: app.py プロジェクト: xswvfr/linode_api4-python
def index():
    client = LinodeClient('no-token')
    types = client.linode.types(Type.label.contains("Linode"))
    regions = client.regions()
    stackscript = StackScript(client, config.stackscript_id)
    return render_template('configure.html',
                           types=types,
                           regions=regions,
                           application_name=config.application_name,
                           stackscript=stackscript)
コード例 #5
0
ファイル: app.py プロジェクト: linode/python-linode-api
def index():
    client = LinodeClient('no-token')
    types = client.linode.types(Type.label.contains("Linode"))
    regions = client.regions()
    stackscript = StackScript(client, config.stackscript_id)
    return render_template('configure.html',  
        types=types,
        regions=regions,
        application_name=config.application_name,
        stackscript=stackscript
    )
コード例 #6
0
def get_client():
    """ XXX
    This will get a LinodeClient prepared with an API Token and User-Agent
    :return: the Linode Client
    """
    return LinodeClient(token=load_token(),
                        user_agent="Cloudify/{}".format(version))
コード例 #7
0
    def setUp(self):
        self.client = LinodeClient('testing', base_url='/')

        self.get_patch = patch(
            'linode_api4.linode_client.requests.Session.get',
            side_effect=mock_get)
        self.get_patch.start()
コード例 #8
0
ファイル: app.py プロジェクト: linode/linode_api4-python
def index():
    """
    This route renders the main page, where users land when visiting the example
    site normally.  This will present a simple form to deploy a Linode and allow
    them to submit the forum.
    """
    client = LinodeClient('no-token')
    types = client.linode.types(Type.label.contains("Linode"))
    regions = client.regions()
    stackscript = StackScript(client, config.stackscript_id)
    return render_template('configure.html',  
        types=types,
        regions=regions,
        application_name=config.application_name,
        stackscript=stackscript
    )
コード例 #9
0
def test_no_instances_found_with_label_gives_none(default_args, access_token):
    set_module_args(default_args)
    module = linode_v4.initialise_module()
    client = LinodeClient(module.params['access_token'])

    target = 'linode_api4.linode_client.LinodeGroup.instances'
    with mock.patch(target, return_value=[]):
        result = linode_v4.maybe_instance_from_label(module, client)

    assert result is None
コード例 #10
0
ファイル: app.py プロジェクト: xswvfr/linode_api4-python
def make_instance(token, type_id, region_id, distribution_id):
    client = LinodeClient('{}'.format(token))
    stackscript = StackScript(client, config.stackscript_id)
    (linode,
     password) = client.linode.instance_create(type_id,
                                               region_id,
                                               group=config.application_name,
                                               image=distribution_id,
                                               stackscript=stackscript.id)

    if not linode:
        raise RuntimeError("it didn't work")
    return linode, password
コード例 #11
0
    def client(self) -> LinodeClient:
        """Creates a 'client' property that is used to access the Linode API."""
        if not self._client:
            api_token = self.module.params['api_token']
            api_version = self.module.params['api_version']

            self._client = LinodeClient(
                api_token,
                base_url='https://api.linode.com/{0}'.format(api_version),
                user_agent=COLLECTION_USER_AGENT,
            )

        return self._client
コード例 #12
0
ファイル: deploy.py プロジェクト: vesche/elbb
def create_instance():
    client = LinodeClient(DEPLOY['api_key'])
    linode_server, root_password = client.linode.instance_create(
        'g6-dedicated-2',
        'us-central',
        image='linode/arch',
        label=DEPLOY['name']
    )
    print(crayons.green(f'[+] Created new Linode instance "{linode_server.label}"!'))
    if DEBUG:
        print('[!] IP:', linode_server.ipv4[0])
        print('[!] RP:', root_password)
    return (linode_server, linode_server.ipv4[0], root_password)
コード例 #13
0
ファイル: create_linode.py プロジェクト: frookazoid/LINODE
class NewProxy():
    def __init__(self):
        self.API_KEY = API_KEY
        self.client = LinodeClient(API_KEY)
        self.region = None
        self.ltype = None
        self.image = "linode/ubuntu16.04lts"
        self.stackscript = 68166
        self.count = raw_input('How many proxies would you like to make?: ')
        self.set_region()
        self.set_type()

    def set_region(self):
        region_list = self.client.regions()
        for i in range(len(region_list)):
            print('{} {}'.format(i, region_list[i]))
        r = input('Please select an available region: ')
        self.region = region_list[r]

    def set_type(self):
        type_list = self.client.linode.types()
        for i in range(len(type_list)):
            print('{} {}'.format(i, type_list[i]))
        t = input('Please select an available linode type: ')
        self.ltype = type_list[t]

    def create_linodes(self):
        for i in range(int(self.count)):
            new_linode, password = self.client.linode.instance_create(
                self.ltype,
                self.region,
                image=self.image,
                stackscript=self.stackscript,
                stackscript_data={
                    "squid_user":"******".format(AUTH_USER),
                    "squid_password":"******".format(AUTH_PASS)
                }
            )
            print('Creating Proxy {}...'.format(new_linode.ipv4[0]))
            with open('LINODE PROXY LIST.txt', 'a+') as f:
                f.write('{}:{}:{}:{}\n'.format(
                    new_linode.ipv4[0],
                    3128,
                    AUTH_USER,
                    AUTH_PASS
                ))
            with open('LINODE PROXY PASSWORDS.txt', 'a+') as f:
                f.write('{} \t{}\n'.format(new_linode.ipv4[0], password))
コード例 #14
0
ファイル: client.py プロジェクト: muradm/ansible-linode-cloud
def linode_client(args, vars, env=environ):
    try:
        from linode_api4 import LinodeClient
    except ImportError:
        raise AnsibleError(u'could not import linode_api4 module')

    at = args.get(
        'access_token',
        vars.get('linode_access_token', env.get('LINODE_ACCESS_TOKEN', None)))

    if at is None:
        raise AnsibleError(u'could not resolve linode access token')

    user_agent = 'Ansible-linode_api4/%s' % ansible_version

    return LinodeClient(at, user_agent=user_agent)
コード例 #15
0
ファイル: instance.py プロジェクト: linode/ansible_linode
    def _build_client(self) -> None:
        """Build the Linode client."""

        api_token = self.get_option('api_token')

        if api_token is None:
            try:
                api_token = os.environ['LINODE_API_TOKEN']
            except KeyError:
                pass

        if api_token is None:
            raise AnsibleError(('Could not retrieve Linode API Token '
                                'from plugin configuration or environment'))

        self.client = LinodeClient(api_token, user_agent=COLLECTION_USER_AGENT)
コード例 #16
0
    def _build_client(self):
        """Build the Linode client."""

        access_token = self.get_option('access_token')

        if access_token is None:
            try:
                access_token = os.environ['LINODE_ACCESS_TOKEN']
            except KeyError:
                pass

        if access_token is None:
            raise AnsibleError(('Could not retrieve Linode access token '
                                'from plugin configuration or environment'))

        self.client = LinodeClient(access_token)
コード例 #17
0
def test_instance_by_label_cannot_authenticate(capfd, access_token,
                                               default_args):
    set_module_args(default_args)
    module = linode_v4.initialise_module()
    client = LinodeClient(module.params['access_token'])

    target = 'linode_api4.linode_client.LinodeGroup.instances'
    with mock.patch(target, side_effect=LinodeApiError('foo')):
        with pytest.raises(SystemExit):
            linode_v4.maybe_instance_from_label(module, client)

    out, err = capfd.readouterr()
    results = json.loads(out)

    assert results['failed'] is True
    assert 'Unable to query the Linode API' in results['msg']
コード例 #18
0
def main():
    agent_label = os.environ['AGENT_NAME']
    key = os.getenv("LINODE_API_KEY")
    if key is None:
        raise RuntimeError("please specify Linode API key")

    client = LinodeClient(key)

    def destroy(linode):
        linode.delete()
        #client.linode_delete(LinodeID = linode[u'LINODEID'], skipChecks = 1)

    linodes = client.linode.instances()
    #logging.info("linodes: {}".format(linodes))

    with closing(ThreadPool(5)) as pool:
        agent = filter(lambda linode: linode.label == agent_label, linodes)
        pool.map(destroy, agent)
        pool.close()
        pool.join()
コード例 #19
0
ファイル: linode.py プロジェクト: dsg22/community.general
    def _build_client(self, loader):
        """Build the Linode client."""

        t = Templar(loader=loader)

        access_token = self.get_option('access_token')
        if t.is_template(access_token):
            access_token = t.template(variable=access_token,
                                      disable_lookups=False)

        if access_token is None:
            try:
                access_token = os.environ['LINODE_ACCESS_TOKEN']
            except KeyError:
                pass

        if access_token is None:
            raise AnsibleError(('Could not retrieve Linode access token '
                                'from plugin configuration or environment'))

        self.client = LinodeClient(access_token)
コード例 #20
0
def _client():
    return LinodeClient("{}".format(LINODE_PAT))
コード例 #21
0
from os.path import join, dirname
"""
Set current working directory to repository root.
"""
os.chdir(join(dirname(__file__), '..'))
"""
Load linode API key from dotenv file
"""
from dotenv import load_dotenv
load_dotenv('.env')
LINODE_API_KEY = os.environ.get("LINODE_API_KEY")
"""
Instantiate linode API client with key
"""
from linode_api4 import LinodeClient  # type: ignore
client = LinodeClient(LINODE_API_KEY)
"""
Print available linode types, regions, and images
"""
# ltypes = client.linode.types()
# regions = client.regions()
# images = client.images()
# for ltype in ltypes:
#     print(ltype)
# for region in regions:
#     print(region)
# for image in images:
#     print(image)


class DesiredLinode:
コード例 #22
0
def reboot_server(): #function to reboot server when it is down
    client = LinodeClient(LINODE_TOKEN) #connecting to our linode server with token
    my_server = client.load(Instance, 376715) #opening a particular instance of our server
    my_server.reboot()
    logging.info('Attempting to reboot server...')
コード例 #23
0
    for ss in stackscripts:
        if ss.label == basename:
            stackscript = ss
            break

    if not stackscript:
        print("ERROR: no appropriate stackscript found")
        exit(1)

    return (stackscript)


#  we don't care about sysargv[0], the invoked command name
args = parse_args(sys.argv[1:])
config = load_config(args['config_file'])
client = LinodeClient(config['api_token'])
stackscript = get_stackscript(config['stackscript_label'], client)

for vm in config['virtual_machines']:
    # Instance_create() returns the newly-created Instance object and the root
    # password that was generated for it. This Instance will boot automatically,
    # and should be available shortly.
    try:
        new_linode, password = client.linode.instance_create(
            vm['size'],
            vm['region'],
            vm['image'],
            stackscript=stackscript,
            stackscript_data={
                "GIT_REPO": config['git_repo'],
                "GIT_BRANCH": config['git_branch'],
コード例 #24
0
- name: Reboot a server
  linode:
     api_key: 'longStringFromLinodeApi'
     name: linode-test1
     linode_id: "{{ linode_creation.instance.id }}"
     state: restarted
  delegate_to: localhost
'''

import os
import time

try:
    from linode_api4 import LinodeClient
    LINODE_CLIENT = LinodeClient('')
    HAS_LINODE = True
except ImportError:
    HAS_LINODE = False

from ansible.module_utils.basic import AnsibleModule


def randompass():
    '''
    Generate a long random password that comply to Linode requirements
    '''
    # Linode API currently requires the following:
    # It must contain at least two of these four character classes:
    # lower case letters - upper case letters - numbers - punctuation
    # we play it safe :)
コード例 #25
0
import sys
import json
from linode_api4 import LinodeClient, Instance

client = LinodeClient(sys.argv[1])
ipv4 = []
ipv6 = []
private = []

for instance_id in sys.argv[2:]:
    instance = client.load(Instance, instance_id)
    ipv4.append(instance.ips.ipv4.public[0].address)
    ipv6.append(instance.ips.ipv6.slaac.address)
    private.append(instance.ips.ipv4.private[0].address)

print(json.dumps({'ipv4': ','.join(ipv4), 'ipv6': ','.join(ipv6), 'private': ','.join(private)}))
コード例 #26
0
#!/usr/local/bin/python3

from linode_api4 import LinodeClient, Image
import config

token = input("Please provide an OAuth Token: ")
client = LinodeClient(token)
s = client.linode.stackscript_create('Demonstration_Public',
                                     '#!/bin/bash',
                                     client.images(Image.is_public == True),
                                     is_public=True)
print("StackScript created, use this ID: {}".format(s.id))
コード例 #27
0
 def reboot_server():
    client =LinodeClient(LINODE_TOKEN)
    server=client.load(Instance, <>)
     server.reboot() 
コード例 #28
0
ファイル: linode_v4.py プロジェクト: coll-test/ansible.misc
def build_client(module):
    """Build a LinodeClient."""
    return LinodeClient(module.params['access_token'],
                        user_agent=get_user_agent('linode_v4_module'))
コード例 #29
0
def main():
    """

    Main func for automatic vulnerability scan by Tenable.io of Company GCP and Cloudflare resources
    :return: none
    """
    parser = argparse.ArgumentParser(description='Provide all arguments for successful Vulnerability scan')
    parser.add_argument("-all", dest="tg_all", action="store_true", help="Scan All supported infrastructures")
    parser.add_argument("-cloudflare", dest="tg_cloudflare", action="store_true", help="Scan GCP infrastructure")
    parser.add_argument("-gcp", dest="tg_gcp", action="store_true", help="Scan Cloudflare infrastructure")
    parser.add_argument("-aws", dest="tg_aws", action="store_true", help="Scan AWS infrastructures")
    parser.add_argument("-linode", dest="tg_linode", action="store_true", help="Scan Linode infrastructures")
    parser.add_argument("-others", dest="tg_others", action="store_true", help="Scan rest of SaaS: DO, Linode, etc")
    parser.add_argument("-schedule", dest="tg_schedule", action="store_true", help="Schedule scans by Tenable.io")
    parser.set_defaults(tg_all=False)
    parser.set_defaults(tg_cloudflare=False)
    parser.set_defaults(tg_gcp=False)
    parser.set_defaults(tg_aws=False)
    parser.set_defaults(tg_linode=False)
    parser.set_defaults(tg_others=False)
    parser.set_defaults(tg_schedule=False)
    args = parser.parse_args()
    # Create dirs
    gen.create_dirs()

    # Set configuration file location
    main_script_abs = os.path.dirname(os.path.abspath(__file__))
    settings_obj = configparser.ConfigParser()
    settings_obj.read(main_script_abs + '/conf/conf.cfg')

    # Initiate an instance of TenableIOClient.
    settings = settings_obj._sections.copy()
    tenable_client = TenableIOClient(access_key=settings['TENABLE.IO']['access_key'],
                                     secret_key=settings['TENABLE.IO']['secret_key'])
    logger.info('Successfully authenticated to Tenable.io')

    # Set scheduled scan time
    scan_time = datetime.now()

    # Set time delta if you need to launch scanning job right now
    if not args.tg_schedule:
        for section in settings.keys():
            if 'time_delta' in settings[section].keys():
                settings[section]['time_delta'] = 0

    # Launch scan jobs in Tenable.io against GCP resources
    if args.tg_gcp or args.tg_all:
        # Set GCP credentials environment
        logger.info('Parsing google credentials and set ENV variables')
        gcp_api_key_json = settings_obj.get('GCP', 'gcp-api-key-json')
        # Set Service account env variable and form path to json file
        os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = main_script_abs + gcp_api_key_json

        # Configure credentials for Google API authentication
        credentials = GoogleCredentials.get_application_default()
        compute = discovery.build('compute', 'v1', credentials=credentials)
        sql = discovery.build('sqladmin', 'v1beta4', credentials=credentials)
        logger.info('Successfully authenticated to GCP services')

        # Get list of all projects via GCP Resource manager
        resource_client = resource_manager.Client()
        projects_list = list(resource_client.list_projects())
        logger.info('Successfully extracted list GCP projects and public IP addresses')
        # Retrieve all GCP organization public IP address
        target_ip_addresses = gcp.get_organization_public_ip(compute, sql, projects_list)
        # # In case you need to read from local copy of saved projects
        # target_ip_addresses = gen.read_json_file('json/20181006T104414-gcp_addresses.json')
        logger.info('Trying to create scan jobs in Tenable.io for all GCP projects')

        # Launch scan against GCP resources
        scan_time = tnb.create_tenable_scan(scan_target='TENABLE_GCP_SCAN',
                                            client=tenable_client,
                                            target=target_ip_addresses,
                                            settings=settings,
                                            logger=logger,
                                            scan_time=scan_time)
        logger.info('Successfully created scan jobs in Tenable.io')

    if args.tg_cloudflare or args.tg_all:
        # Parse CF credentials environment
        logger.info('Parsing Cloudflare credentials')
        cf_email = settings_obj.get('CLOUDFLARE', 'cf_email')
        cf_api_key = settings_obj.get('CLOUDFLARE', 'cf_api_key')

        # Create Cloudflare connection object
        cf_client = CloudFlare.CloudFlare(email=cf_email, token=cf_api_key)
        # Create targets for scanning job
        target_hostnames = cf.get_cf_website_dns(cf_client=cf_client)

        # # Test purposes (comment please when test will be finished)
        # target_hostnames = gen.read_json_file('json/20181005T185623-cf_addresses.json')
        # scan_time += timedelta(hours=90)
        cf.create_firewall_access_rule(cf_client=cf_client, settings=settings, zones=target_hostnames)
        scan_time = tnb.create_tenable_scan(scan_target='TENABLE_CF_SCAN',
                                            client=tenable_client,
                                            target=target_hostnames,
                                            settings=settings,
                                            logger=logger,
                                            scan_time=scan_time)

    if args.tg_aws or args.tg_all:
        # Create Cloudflare connection object
        target_assets = aws.get_tenables_assets(client=tenable_client)
        scan_time = tnb.create_tenable_scan(scan_target='TENABLE_AWS_SCAN',
                                            client=tenable_client,
                                            target=target_assets,
                                            settings=settings,
                                            logger=logger,
                                            scan_time=scan_time)

    if args.tg_linode or args.tg_all:
        # Get Linode targets
        linode_client = LinodeClient(settings['LINODE']['lin_api_key'])
        linode_targets = lin.get_linode_targets(client=linode_client)
        scan_time = tnb.create_tenable_scan(scan_target='TENABLE_LINODE_SCAN',
                                            client=tenable_client,
                                            target=linode_targets,
                                            settings=settings,
                                            logger=logger,
                                            scan_time=scan_time)

    if args.tg_others or args.tg_all:
        # Launch scan of Other targets
        target_assets = others.prepare_other_targets(settings['TENABLE_OTHERS_SCAN'])
        scan_time = tnb.create_tenable_scan(scan_target='TENABLE_OTHERS_SCAN',
                                            client=tenable_client,
                                            target=target_assets,
                                            settings=settings,
                                            logger=logger,
                                            scan_time=scan_time)

    logger.info('Vulnerability scan will be finished at {0}'.format(scan_time.strftime('%Y%m%dT%H%M%S')))
    logger.info('########################################  END ########################################')
コード例 #30
0
ファイル: Test.py プロジェクト: salmanzafar949/PythonOop
def reboot_server():
    client = LinodeClient(LINODE_TOKEN)
    my_server = client.load(Instance, 376715)
    my_server.reboot()
コード例 #31
0
    for service in device.services:
        if service.find_action("GetExternalIPAddress"):
            external_ips.append(
                service.GetExternalIPAddress()["NewExternalIPAddress"])

if len(external_ips) < 1:
    raise Exception("Found no external IP addresses")

if len(external_ips) > 1:
    raise Exception("Found more than one external IP address")

external_ip = external_ips[0]

# Find our domain and record
linode_client = LinodeClient(config["token"])

for domain in linode_client.domains():
    if domain.domain != domain_name:
        continue

    for record in domain.records:
        if record.name == subdomain_name:
            record.target = external_ip
            record.save()
            break
    else:
        domain.record_create(record_type="A",
                             name=subdomain_name,
                             target=external_ip)
コード例 #32
0
ファイル: monitor.py プロジェクト: macik1423/code_snippets
def reboot_server():
    client = LinodeClient(LINODE_TOKEN)
    my_server = client.load(Instance, 376715)
    my_server.reboot()
コード例 #33
0
#!/usr/local/bin/python3

from linode_api4 import LinodeClient, Image
import config

token = input("Please provide an OAuth Token: ")
client = LinodeClient(token)
s = client.linode.stackscript_create('Demonstration_Public', '#!/bin/bash',
                                     client.images(Image.is_public==True), is_public=True)
print("StackScript created, use this ID: {}".format(s.id))