def test_create_connection_version_param_default(self):
     c1 = connection.Connection(cloud='sample')
     conn = connection.Connection(session=c1.session)
     self.assertEqual('openstack.identity.v2._proxy',
                      conn.identity.__class__.__module__)
from openstack import connection

conn = connection.Connection(auth_url='http://YOUR_floating_IP:5000/v2.0',
                             username='******',
                             password='******',
                             project_name='YOUR_PROJECT_NAAME')

conn.compute.servers()
conn.image.images()
conn.object_store.containers()
Exemple #3
0
# openstack example python-let: neutron-net-list.sdk.py
#
# Author: JuanJo Ciarlante <*****@*****.**>
# License: http://www.apache.org/licenses/LICENSE-2.0
# vim: si et sw=4 ts=4

import os
from openstack import connection
from openstack import profile


def get_creds():
    # create a dictionary as e.g.: {'username': env['OS_USERNAME'], ...
    return {
        key: os.environ.get('OS_{}'.format(key.upper()))
        for key in ('auth_url', 'username', 'password', 'tenant_name',
                    'region_name')
    }


creds = get_creds()
# SDK uses project_name instead of tenant_name
creds['project_name'] = creds['tenant_name']
# SDK handles region_name, services versions via profile
prof = profile.Profile()
prof.set_region(profile.Profile.ALL, creds['region_name'])
prof.set_version('network', 'v2')
conn = connection.Connection(profile=prof, **creds)
for net in conn.network.networks():
    print net.id, net.name, net.subnets
 def test_task_manager_rate_scalar(self):
     conn = connection.Connection(cloud='sample-cloud', rate_limit=20)
     self.assertEqual(1.0 / 20, conn.task_manager._get_wait('object-store'))
     self.assertEqual(1.0 / 20, conn.task_manager._get_wait(None))
Exemple #5
0
 def test_custom_user_agent(self):
     user_agent = "MyProgram/1.0"
     conn = connection.Connection(authenticator=self.auth,
                                  user_agent=user_agent)
     self.assertTrue(conn.transport._user_agent.startswith(user_agent))
from openstack import connection

os.environ.setdefault(
    'OS_CDN_ENDPOINT_OVERRIDE',
    'xxxxxxxxxxx')  # CDN API url,example:https://cdn.myhuaweicloud.com/v1.0/

# AKSK Auth
projectId = "xxxxxxxxxxx"  # Project ID of cn-north-1
cloud = "xxxxxxxxxxx"  # cdn use: cloud = "myhuaweicloud.com"
region = "xxxxxxxxxxx"  # example: region = "cn-north-1"
AK = "xxxxxxxxxxx"
SK = "xxxxxxxxxxx"

conn = connection.Connection(project_id=projectId,
                             cloud=cloud,
                             region=region,
                             ak=AK,
                             sk=SK)

# token Auth
# username = "******"  # IAM User Name
# password = "******"  # IAM User Password
# projectId = "xxxxxxxxxxx"  # Project ID of cn-north-1
# userDomainId = "xxxxxxxxxxx"  # Account ID
# auth_url = "xxxxxxxxxxx"  # IAM auth url,example: https://iam.myhuaweicloud.com/v3
#
# conn = connection.Connection(
#     auth_url=auth_url,
#     user_domain_id=userDomainId,
#     project_id=projectId,
#     username=username,
 def test_create_connection_version_param_int(self):
     c1 = connection.Connection(cloud='sample-cloud')
     conn = connection.Connection(session=c1.session,
                                  identity_api_version=3)
     self.assertEqual('openstack.identity.v3._proxy',
                      conn.identity.__class__.__module__)
Exemple #8
0
#import OpenStack connection class from the SDK
from openstack import connection

# Create a connection object by calling the constructor and pass the security information
conn = connection.Connection(auth_url="http://192.168.0.106/identity",
                             project_name="demo",
                             username="******",
                             password="******",
                             user_domain_id="default",
                             project_domain_id="default")


def create_volume(conn):
    volume_properties = {'size': '2', 'name': 'packtpub-volume'}
    volume = conn.block_store.create_volume(**volume_properties)


create_volume(conn)
Exemple #9
0
    def conn(self):
        """Return an OpenStackSDK connection.

        :returns: object
        """
        return os_conn.Connection(verify=self.verify, **self.os_auth_args)
Exemple #10
0
 def test_session_provided(self):
     mock_session = mock.Mock(spec=session.Session)
     conn = connection.Connection(session=mock_session, cert='cert')
     self.assertEqual(mock_session, conn.session)
Exemple #11
0
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask import jsonify
from flask import json
import ruamel.yaml
from openstack import connection

app = Flask(__name__)
app.debug = True

osconn = connection.Connection(
    auth_url=os.environ['OS_AUTH_URL'],
    project_name=os.environ['OS_PROJECT_NAME'],
    username=os.environ['OS_USERNAME'],
    password=os.environ['OS_PASSWORD'],
    user_domain_id="default",
    project_id=os.environ['OS_PROJECT_ID'],
    project_domain_id=os.environ['OS_PROJECT_DOMAIN_ID'],
    compute_api_version='2.1',
    verify=False)
#print(osconn)

app.config['SECRET_KEY'] = 'Idabagusrathuekasuryawibawa!'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'sqlite:////home/gustu/myweb/database/database.db'
Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
Exemple #12
0
def auth():
    con = connection.Connection(auth_url="http://10.136.60.28:5000/v2.0",
                                project_name="admin",
                                username="******",
                                password="******")
    return con
#!/usr/bin/env python
# coding=utf-8
from openstack import connection

auth_token = "replace-with-your-token-id"
auth_url = "https://iam.example.com/v3"

token_conn = connection.Connection(
    auth_url=auth_url,
    auth_token=auth_token,
)


def test_list_endpoints(conn):
    query = {
        "limit": 3,
    }
    objs = conn.identity.endpoints(**query)
    for i in objs:
        print i


if __name__ == "__main__":
    test_list_endpoints(token_conn)
Exemple #14
0
def get_connection(auth_args):
    """ separate function for get_connection ,might change ::
        still have figureout how to access env var defaults for auth """
    con = connection.Connection(**auth_args)
    return con
def get_usage_from_openstack():
    config = openstack.config.get_cloud_region(cloud='nerds', region_name='RegionOne')
    conn = connection.Connection(config=config)
    return [ hypervisor.to_dict() for hypervisor in conn.compute.hypervisors(details=True)]
Exemple #16
0
def pre_build_topo():
    """pre_build_topo"""

    auth_args = {
        'auth_url': 'http://192.168.12.10/identity/v3',
        'project_name': 'admin',
        'user_domain_name': 'default',
        'project_domain_name': 'default',
        'username': '******',
        'password': '******',
    }

    print('# Create a connection to the cloud with Auth URL: %s' %
          auth_args['auth_url'])
    conn = connection.Connection(**auth_args)

    img_args = {
        'name': 'ubuntu-cloud',
        # Path of the image
        # 'path': os.getenv('HOME') + '/ostack_image/ubuntu-trusty-customized.qcow2',
        'path': '/opt/stack/sfcostack/ubuntu-trusty.qcow2',
        'disk_format': 'qcow2',
        'container_format': 'bare',
        'visibility': 'public',
    }
    if not conn.image.find_image(img_args['name']):
        print("[IMAGE] Upload %s image..." % img_args['name'])
        data = open(img_args['path'], 'rb').read()
        image_attrs = {
            'name': img_args['name'],
            'data': data,
            'disk_format': img_args['disk_format'],
            'container_format': img_args['container_format'],
            'visibility': img_args['visibility'],
        }
        conn.image.upload_image(**image_attrs)

    kp_args = {'name': 'sfc_test', 'path': './sfc_test.pem'}
    if not conn.compute.find_keypair(kp_args['name']):
        print("[KEYPAIR] Create Key Pair: %s" % kp_args['name'])
        key_pair = conn.compute.create_keypair(name=kp_args['name'])
        # remove old pem files
        for key_file in glob.glob('./*.pem'):
            os.chmod(key_file, 0o777)
            os.remove(key_file)

        with open(kp_args['path'], 'w+') as key_file:
            key_file.write("%s" % key_pair.private_key)
            os.chmod('./%s.pem' % kp_args['name'], 0o400)

    sec_grp_args = {'name': 'sfc_test'}
    if not conn.network.find_security_group(sec_grp_args['name']):
        project = conn.identity.find_project(auth_args['project_name'])
        print('[SECGRP] Create a test security group: %s...' %
              sec_grp_args['name'])
        sec_gp = conn.network.create_security_group(
            name=sec_grp_args['name'],
            project_id=project.id,
            description=
            'Only for testing, allow all ICMP, TCP and UDP ingress access')
        print(
            '[SECGRP] Add rules, allow ICMP, TCP and UDP ingress for all addresses...'
        )
        for ptl in ('icmp', 'tcp', 'udp'):
            conn.network.create_security_group_rule(
                security_group_id=sec_gp.id,
                direction='ingress',
                # allow all ip addresses
                remote_ip_prefix='0.0.0.0/0',
                protocol=ptl,
                port_range_max=None,
                port_range_min=None,
                ethertype='IPv4')

    fv_args = {
        'name': 'sfc_test',
        'vcpus': '1',
        # in GB, for ubuntu-cloud minimal 1.8G
        'disk': '2',
        # in MB
        'ram': '1024'
    }
    if not conn.compute.find_flavor(fv_args['name']):
        print('[FLAVOR] Create a flavor for testing instances: %s...' %
              fv_args['name'])
        conn.compute.create_flavor(**fv_args)
import json
from openstack import connection
conn = connection.Connection(auth_url="http://10.85.140.143:5000/v2.0",
                             project_name="GVE",
                             username="******",
                             password="******")

print("List Images:")

for image in conn.compute.images():
    keys = image.keys()
    for x, index in enumerate(keys):
        #if index == "name":
        print "%s | %s\n" % (keys[x], image[index])

print("List Servers:")
for server in conn.compute.servers():
    keys = server.keys()
    for x, index in enumerate(keys):
        print "%s | %s\n" % (keys[x], server[index])

print("List Flavors:")
for flavor in conn.compute.flavors():
    keys = flavor.keys()
    for x, index in enumerate(keys):
        print "%s | %s\n" % (keys[x], flavor[index])
Exemple #18
0
from openstack import connection
import time

conn = connection.Connection(
    region_name='RegionOne',
    auth=dict(auth_url='http://192.168.0.23:5000/v3',
              username='******',
              password='******',
              project_id='139b699e41f5463cbdccf14f691c722a',
              user_domain_id='0cf17c3ad2a548139f61c48911f75118'),
    compute_api_version='2',
    identity_interface='public')

#image = conn.create_image('bionic', filename='bionic.qcow2', wait=True)

# Find a flavor with at least 512M of RAM
flavor = conn.get_flavor_by_ram(1024)

print(flavor)

network = conn.network.find_network("RafaelNet")
# Boot a server, wait for it to boot, and then do whatever is needed
# to get a public ip for it.
conn.create_server('my-server',
                   image='bionic',
                   flavor=flavor,
                   wait=True,
                   auto_ip=True,
                   network=network)
print("Lancou a instancia")
time.sleep(30)
 def test_create_session(self):
     conn = connection.Connection(cloud='sample-cloud')
     self.assertIsNotNone(conn)
 def test_default_plugin(self, mock_get_plugin):
     connection.Connection()
     self.assertTrue(mock_get_plugin.called)
     self.assertEqual(mock_get_plugin.call_args, mock.call("password"))
 def test_other_parameters(self):
     conn = connection.Connection(cloud='sample-cloud', cert='cert')
     self.assertEqual(conn.session.cert, 'cert')
 def test_pass_authenticator(self, mock_get_plugin):
     mock_plugin = mock.Mock()
     mock_get_plugin.return_value = None
     conn = connection.Connection(authenticator=mock_plugin)
     self.assertFalse(mock_get_plugin.called)
     self.assertEqual(mock_plugin, conn.authenticator)
Exemple #23
0
from openstack import connection
conn = connection.Connection(auth_url="http://centospackstack:5000/v2.0",
                             project_name="tata",
                             username="******",
                             password="******")
print conn
for image in conn.compute.images():
    print(image.name)
Exemple #24
0
import json
import logging

from openstack import connection
from collections import OrderedDict

logger = logging.getLogger(__name__)

conn = connection.Connection(cloud='divine')


def get_projects():

    global projects

    logger.info('Getting projects ..')
    projects = {}
    projectList = []
    for project in conn.list_projects():
        projectDict = OrderedDict()
        projects[project.get('id')] = project.get('name')
        projectDict['name'] = project.get('name')
        projectDict['id'] = project.get('id')
        projectDict['description'] = project.get('description')

        for user in conn.list_users():
            if project.get('id') == user.get('default_project_id'):
                projectDict['user'] = user.get('name')

        projectList.append(projectDict)
Exemple #25
0
 def test_create_transport(self):
     conn = connection.Connection(authenticator='2', verify=True,
                                  user_agent='1')
     self.assertTrue(conn.transport.verify)
     self.assertIn('1', conn.transport._user_agent)
Exemple #26
0
        if ip.fixed_ip_address == None:
            server_port = _get_server_port(server)
            return conn.network.update_ip(ip, fixed_ip_address=server_fixed_ip_address, port_id=server_port.id)
    server_port = _get_server_port(server)
    return conn.network.create_ip(floating_network_id=external_network.id,
                                  fixed_ip_address=server_fixed_ip_address,
                                  port_id=server_port.id)

auth_args = {
    'auth_url': 'http://100.67.130.148:5000/v2.0',
    'project_name': 'admin',
    'username': '******',
    'password': '******',
}

conn = connection.Connection(**auth_args)

IMAGE_NAME = 'ubuntu14.04'
FLAVOR_NAME = 'm1.small'
NETWORK_NAME = 'private'
KEYPAIR_NAME = 'default'
PUBLIC_NETWORK_NAME = 'public'

image = conn.compute.find_image(IMAGE_NAME)
flavor = conn.compute.find_flavor(FLAVOR_NAME)

# By default, OpenStack filters all traffic. You must create a security group and apply it to your
# instance. The security group allows HTTP and SSH access.
network = conn.network.find_network(NETWORK_NAME)
public_network = conn.network.find_network(PUBLIC_NETWORK_NAME)
Exemple #27
0
# specific language governing permissions and limitations under the License.

import sys

from openstack import connection

# create connection
username = "******"
password = "******"
userDomainId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"  # user account ID
auth_url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"  # endpoint url

if __name__ == '__main__':
    conn = connection.Connection(auth_url=auth_url,
                                 user_domain_id=userDomainId,
                                 domain_id=userDomainId,
                                 username=username,
                                 password=password)

    data = {
        "customerId": "xxxxxxxxxxxxxxxxxxxxx",
        "identifyType": 0,
        "verifiedType": 0,
        "verifiedFileURL": ["zhengmian.jpg", "fanmian.jpg", "chizheng2.jpg"],
        "name": "NAME",
        "verifiedNumber": "xxxxxxxxxxx",
        "changeType": -1,
        "xaccountType": "xxxx_IDP"
    }
    '''
    This API can be used to submit an individual real-name authentication application.
import warnings

from openstack import utils
from openstack import connection

utils.enable_logging(debug=True, stream=sys.stdout)
warnings.filterwarnings('ignore')

auth_url = '******'
userDomainId = '******'
projectId = '******'
username = '******'
password = '******'

conn = connection.Connection(auth_url=auth_url,
                             user_domain_id=userDomainId,
                             project_id=projectId,
                             username=username,
                             password=password,
                             verify=False)


def test_extensions(_conn):
    for index in _conn.block_store.extensions():
        print(index)


if __name__ == '__main__':
    # test_extensions(conn)
    pass
Exemple #29
0
from keystoneclient.v3 import client
import sys

auth = v3.Password(auth_url='https://home.jcloud.sjtu.edu.cn:5000/v3',
                   username='******',
                   password='******',
                   project_name='jimmyyao18_project',
                   user_domain_name='Default',
                   project_domain_name='Default')

sess = session.Session(auth=auth)
sess.get('https://home.jcloud.sjtu.edu.cn:5000/v3')

conn = connection.Connection(
    session=sess,
    region_name='RegionOne',
    identity_interface='internal',
)
conn.authorize()


def reboot_HARD(conn):
    if (len(sys.argv) < 2):
        print("Error")
    else:
        server = conn.compute.find_server(sys.argv[1])
        conn.compute.reboot_server(server, "SOFT")


reboot_HARD(conn)
Exemple #30
0
def get_openstack_connection_raw(auth_args):
    """obtains an OpenStack connection from a supplied dictionary of auth args"""
    print("Connecting to Openstack at {0}".format(auth_args['auth_url']))
    conn = connection.Connection(**auth_args)
    return conn