def setup(hass, config): """Set up the UpCloud component.""" import upcloud_api conf = config[DOMAIN] username = conf.get(CONF_USERNAME) password = conf.get(CONF_PASSWORD) scan_interval = conf.get(CONF_SCAN_INTERVAL) manager = upcloud_api.CloudManager(username, password) try: manager.authenticate() hass.data[DATA_UPCLOUD] = UpCloud(manager) except upcloud_api.UpCloudAPIError: _LOGGER.error("Authentication failed.") return False def upcloud_update(event_time): """Call UpCloud to update information.""" _LOGGER.debug("Updating UpCloud component") hass.data[DATA_UPCLOUD].update() dispatcher_send(hass, SIGNAL_UPDATE_UPCLOUD) # Call the UpCloud API to refresh data track_time_interval(hass, upcloud_update, scan_interval) return True
async def async_step_user(self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle user initiated flow.""" if user_input is None: return self._async_show_form(step_id="user") await self.async_set_unique_id(user_input[CONF_USERNAME]) manager = upcloud_api.CloudManager(user_input[CONF_USERNAME], user_input[CONF_PASSWORD]) errors = {} try: await self.hass.async_add_executor_job(manager.authenticate) except upcloud_api.UpCloudAPIError: errors["base"] = "invalid_auth" _LOGGER.debug("invalid_auth", exc_info=True) except requests.exceptions.RequestException: errors["base"] = "cannot_connect" _LOGGER.debug("cannot_connect", exc_info=True) if errors: return self._async_show_form(step_id="user", user_input=user_input, errors=errors) return self.async_create_entry(title=user_input[CONF_USERNAME], data=user_input)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up the UpCloud config entry.""" manager = upcloud_api.CloudManager(entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD]) try: await hass.async_add_executor_job(manager.authenticate) except upcloud_api.UpCloudAPIError: _LOGGER.error("Authentication failed", exc_info=True) return False except requests.exceptions.RequestException as err: _LOGGER.error("Failed to connect", exc_info=True) raise ConfigEntryNotReady from err upcloud_data = hass.data.setdefault(DATA_UPCLOUD, UpCloudHassData()) # Handle pre config entry (0.117) scan interval migration to options migrated_scan_interval = upcloud_data.scan_interval_migrations.pop( entry.data[CONF_USERNAME], None) if migrated_scan_interval and (not entry.options.get(CONF_SCAN_INTERVAL) or entry.options[CONF_SCAN_INTERVAL] == DEFAULT_SCAN_INTERVAL.total_seconds()): update_interval = migrated_scan_interval hass.config_entries.async_update_entry( entry, options={CONF_SCAN_INTERVAL: update_interval.total_seconds()}, ) elif entry.options.get(CONF_SCAN_INTERVAL): update_interval = timedelta(seconds=entry.options[CONF_SCAN_INTERVAL]) else: update_interval = DEFAULT_SCAN_INTERVAL coordinator = UpCloudDataUpdateCoordinator( hass, update_interval=update_interval, cloud_manager=manager, username=entry.data[CONF_USERNAME], ) # Call the UpCloud API to refresh data await coordinator.async_config_entry_first_refresh() # Listen to config entry updates entry.async_on_unload( entry.add_update_listener(_async_signal_options_update)) entry.async_on_unload( async_dispatcher_connect( hass, _config_entry_update_signal_name(entry), coordinator.async_update_config, )) upcloud_data.coordinators[entry.data[CONF_USERNAME]] = coordinator # Forward entry setup hass.config_entries.async_setup_platforms(entry, CONFIG_ENTRY_DOMAINS) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up the UpCloud config entry.""" manager = upcloud_api.CloudManager(entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD]) try: await hass.async_add_executor_job(manager.authenticate) except upcloud_api.UpCloudAPIError: _LOGGER.error("Authentication failed", exc_info=True) return False except requests.exceptions.RequestException as err: _LOGGER.error("Failed to connect", exc_info=True) raise ConfigEntryNotReady from err if entry.options.get(CONF_SCAN_INTERVAL): update_interval = timedelta(seconds=entry.options[CONF_SCAN_INTERVAL]) else: update_interval = DEFAULT_SCAN_INTERVAL coordinator = UpCloudDataUpdateCoordinator( hass, update_interval=update_interval, cloud_manager=manager, username=entry.data[CONF_USERNAME], ) # Call the UpCloud API to refresh data await coordinator.async_config_entry_first_refresh() # Listen to config entry updates entry.async_on_unload( entry.add_update_listener(_async_signal_options_update)) entry.async_on_unload( async_dispatcher_connect( hass, _config_entry_update_signal_name(entry), coordinator.async_update_config, )) hass.data[DATA_UPCLOUD] = UpCloudHassData() hass.data[DATA_UPCLOUD].coordinators[ entry.data[CONF_USERNAME]] = coordinator # Forward entry setup hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
def _get_manager(vm_=None): if vm_ is not None: api_user = vm_['api_user'] password = vm_['password'] else: api_user = config.get_cloud_config_value('api_user', get_configured_provider(), __opts__, search_global=False) password = config.get_cloud_config_value('password', get_configured_provider(), __opts__, search_global=False) manager = upcloud_api.CloudManager(api_user, password) manager.authenticate() return manager
import requests import upcloud_api from upcloud_api import Server, Storage, ZONE, login_user_block manager = upcloud_api.CloudManager('darnellapi', 'Master1960#') manager.authenticate() noofservers = 3 login_user = login_user_block( username='******', ssh_keys=['ssh-rsa AAAAB3NzaC1yc2EAA[...]ptshi44x [email protected]'], create_password=False ) for inc in range(0, noofservers): server_config = Server( title='Server'+str(inc), plan='1xCPU-1GB', hostname='server'+str(inc)+'.darnell.com', zone=ZONE.Chicago, storage_devices=[ Storage(os='CentOS 6.5', size=25), ], login_user=login_user, user_data='/createproxy.sh' ) manager.create_server(server_config) print("end of loop")
def __init__(self, username, password, module): self.manager = upcloud_api.CloudManager(username, password) self.module = module
exit(0) else: print('ERROR - Got on unrecognized command line option "{0}"'.format( opt)) exit(2) if upcloud_user is None \ or upcloud_password is None \ or rtmp_config_filepath is None \ or ssh_key_filepath is None \ or rtmp_streaming_password is None: print('ERROR - configuration is not complete.') exit(2) # Connect to UpCloud manager = up.CloudManager(upcloud_user, upcloud_password) manager.authenticate() print('Connected to UpCloud API as user "{0}"'.format(upcloud_user)) res = subprocess.run( 'cat {0}'.format(ssh_key_filepath), shell=True, stdout=subprocess.PIPE, text=True, ) ssh_key_value = res.stdout.strip() rtmp_user_desc = up.login_user_block( username='******', ssh_keys=[ssh_key_value], create_password=False, )
sys.exit(-1) return username, password if __name__ == "__main__": # read settings args = read_cli_args() config = ConfigParser.SafeConfigParser() config.read(os.path.dirname(os.path.realpath(__file__)) + '/upcloud.ini') # setup API connection username, password = read_api_credentials(config) manager = upcloud_api.CloudManager(username, password) # decide whether to return hostnames or ip_addresses with_ip_addresses = False if config.has_option('upcloud', 'return_ip_addresses') and config.get( 'upcloud', 'return_ip_addresses'): with_ip_addresses = True if args.return_ip_addresses: with_ip_addresses = True # choose correct action if args.list: list_servers(manager, with_ip_addresses) elif args.host:
def manager(): import upcloud_api return upcloud_api.CloudManager("testuser", "mock-api-password")
print_help() exit(0) else: print('ERROR - Got on unrecognized command line option "{0}"'.format(opt)) exit(2) if upcloud_user is None \ or upcloud_password is None \ or rtmp_config_filepath is None \ or ssh_key_filepath is None \ or rtmp_streaming_password is None: print('ERROR - configuration is not complete.') exit(2) # Connect to UpCloud manager = up.CloudManager(upcloud_user, upcloud_password, timeout=60) manager.authenticate() print('Connected to UpCloud API as user "{0}"'.format(upcloud_user)) res = subprocess.run( 'cat {0}'.format(ssh_key_filepath), shell=True, stdout=subprocess.PIPE, text=True, ) ssh_key_value = res.stdout.strip() rtmp_user_desc = up.login_user_block( username='******', ssh_keys=[ssh_key_value], create_password=False, )
# read settings args = read_cli_args() config = configparser.ConfigParser() config.read(os.path.dirname(os.path.realpath(__file__)) + "/upcloud.ini") # setup API connection username, password = read_api_credentials(config) default_timeout = os.getenv("UPCLOUD_API_TIMEOUT") or config.get( "upcloud", "default_timeout") if not default_timeout: default_timeout = None else: default_timeout = float(default_timeout) manager = upcloud_api.CloudManager(username, password, default_timeout) # decide whether to return hostnames or ip_addresses if config.has_option("upcloud", "return_ip_addresses"): with_ip_addresses = (str(config.get( "upcloud", "return_ip_addresses")).lower() == "true") else: return_error_msg_due_to_faulty_ini_file("return_ip_addresses") if config.has_option("upcloud", "return_non_fqdn_names"): return_non_fqdn_names = (str( config.get("upcloud", "return_non_fqdn_names")).lower() == "true") else: return_error_msg_due_to_faulty_ini_file("return_non_fqdn_names") if config.has_option("upcloud", "default_ipv_version"):
#!/usr/bin/env python3 # # Create a new instance at UpCloud. # # pip3 install --user upcloud-api # chmod 600 upcloud_create_server.py import upcloud_api from upcloud_api import Server, Storage, ZONE, login_user_block # EDIT manager = upcloud_api.CloudManager('USERNAME', 'PASSWORD') user_viktor = login_user_block( username='******', ssh_keys=['ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJnaM2JLvO4DWkmmSXys+jn0KhTRVkCfAAhv/1Pszs0DJTheQgOR9e3ThNCgR7CxIqZ5kXrZ+BIDtDs5IGrg9IA= szv-ecdsa'], create_password=False ) new_server_config = Server( hostname='upcloud.keszul.tk', zone=ZONE.Frankfurt, plan='2xCPU-2GB', storage_devices=[ Storage(os='Debian 8.0', size=50) ], login_user=user_viktor, # Docker + pip user_data='https://github.com/szepeviktor/debian-server-tools/raw/master/upcloud-init.sh' )
from docopt import docopt import os import time import upcloud_api from pssh.clients import ParallelSSHClient, SSHClient from subprocess import call NAME = "synthetic-bot-up" SIZE = "2xCPU-4GB" # cpx31 PERFORMERS = 5 USER = os.getenv("SYN_USER") APIUSER = os.getenv("UP_USER") TOKEN = os.getenv("UP_TOKEN") manager = upcloud_api.CloudManager(APIUSER, TOKEN) manager.authenticate() with open("key.txt", "r") as infile: SERVER_KEY = infile.read().strip() def get_servers(): """ Retrieve all servers """ servers = manager.get_servers() servers = [s for s in servers if NAME in s.title] return servers def status(): """ Print the status of all bot servers """
def __init__(self, logger, config, **kwargs): super(SdkApiBase, self).__init__(logger, config, **kwargs) self._manager = upcloud_api.CloudManager(self.username, self.password)