def test_init(self): config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir) self.assertEqual(DEFAULTS, config.config) config = Config('test.conf', config_dir=self.config_dir) self.assertEqual({}, config.config)
def test_init(self): config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir) self.assertEquals(DEFAULTS, config.config) config = Config("test.conf", config_dir=self.config_dir) self.assertEquals({}, config.config)
def __init__(self): migrate_hostlist('hostlist.conf.1.2', 'hostlist.conf') self.config = Config('hostlist.conf', default_hostlist(), config_dir=get_config_dir(), file_version=3) self.config.run_converter((1, 2), 3, migrate_config_2_to_3) self.config.save()
def test_set_get_item(self): config = Config("test.conf", config_dir=self.config_dir) config["foo"] = 1 self.assertEquals(config["foo"], 1) self.assertRaises(ValueError, config.set_item, "foo", "bar") config["foo"] = 2 self.assertEquals(config.get_item("foo"), 2) config["unicode"] = u"ВИДЕОФИЛЬМЫ" self.assertEquals(config["unicode"], u"ВИДЕОФИЛЬМЫ") config._save_timer.cancel()
def check_config(): config = Config('test.conf', config_dir=self.config_dir) self.assertEqual(config['string'], 'foobar') self.assertEqual(config['float'], 0.435) self.assertEqual(config['password'], 'abc123*\\[!]?/<>#{@}=|"+$%(^)~')
def check_config(config): self.assertTrue(not config._save_timer.active()) del config config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir) self.assertEquals(config["string"], "baz") self.assertEquals(config["int"], 2)
def migrate_hostlist(old_filename, new_filename): """Check for old hostlist filename and save details to new filename""" old_hostlist = get_config_dir(old_filename) if os.path.isfile(old_hostlist): config_v2 = Config(old_filename, config_dir=get_config_dir()) config_v2.save(get_config_dir(new_filename)) del config_v2 try: os.rename(old_hostlist, old_hostlist + '.old') except OSError as ex: log.exception(ex) try: os.remove(old_hostlist + '.bak') except OSError: pass
def check_config(config): self.assertTrue(not config._save_timer.active()) del config config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir) self.assertEqual(config['string'], 'baz') self.assertEqual(config['int'], 2)
def test_get(self): config = Config('test.conf', config_dir=self.config_dir) config['foo'] = 1 self.assertEqual(config.get('foo'), 1) self.assertEqual(config.get('foobar'), None) self.assertEqual(config.get('foobar', 2), 2) config['foobar'] = 5 self.assertEqual(config.get('foobar', 2), 5)
def test_save(self): config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir) # We do this twice because the first time we need to save the file to disk # and the second time we do a compare and we should not write ret = config.save() self.assertTrue(ret) ret = config.save() self.assertTrue(ret) config["string"] = "baz" config["int"] = 2 ret = config.save() self.assertTrue(ret) del config config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir) self.assertEquals(config["string"], "baz") self.assertEquals(config["int"], 2)
def get_config(self, config_file, defaults=None, file_version=1): """Get a reference to the Config object for this filename""" log.debug('Getting config: %s', config_file) # Create the config object if not already created if config_file not in self.config_files: self.config_files[config_file] = Config( config_file, defaults, config_dir=self.config_directory, file_version=file_version) return self.config_files[config_file]
def test_save(self): config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir) # We do this twice because the first time we need to save the file to disk # and the second time we do a compare and we should not write ret = config.save() self.assertTrue(ret) ret = config.save() self.assertTrue(ret) config['string'] = 'baz' config['int'] = 2 ret = config.save() self.assertTrue(ret) del config config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir) self.assertEqual(config['string'], 'baz') self.assertEqual(config['int'], 2)
def test_set_get_item(self): config = Config('test.conf', config_dir=self.config_dir) config['foo'] = 1 self.assertEqual(config['foo'], 1) self.assertRaises(ValueError, config.set_item, 'foo', 'bar') config['foo'] = 2 self.assertEqual(config.get_item('foo'), 2) config['foo'] = '3' self.assertEqual(config.get_item('foo'), 3) config['unicode'] = 'ВИДЕОФИЛЬМЫ' self.assertEqual(config['unicode'], 'ВИДЕОФИЛЬМЫ') config['unicode'] = b'foostring' self.assertFalse(isinstance(config.get_item('unicode'), bytes)) config._save_timer.cancel()
def test_set_get_item_none(self): config = Config('test.conf', config_dir=self.config_dir) config['foo'] = None self.assertIsNone(config['foo']) self.assertIsInstance(config['foo'], type(None)) config['foo'] = 1 self.assertEqual(config.get('foo'), 1) config['foo'] = None self.assertIsNone(config['foo']) config['bar'] = None self.assertIsNone(config['bar']) config['bar'] = None self.assertIsNone(config['bar']) config._save_timer.cancel()
def test_save_timer(self): config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir) config["string"] = "baz" config["int"] = 2 self.assertTrue(config._save_timer.active()) def check_config(config): self.assertTrue(not config._save_timer.active()) del config config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir) self.assertEquals(config["string"], "baz") self.assertEquals(config["int"], 2) from twisted.internet.task import deferLater from twisted.internet import reactor d = deferLater(reactor, 7, check_config, config) return d
def test_save_timer(self): self.clock = task.Clock() deluge.config.callLater = self.clock.callLater config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir) config['string'] = 'baz' config['int'] = 2 self.assertTrue(config._save_timer.active()) # Timeout set for 5 seconds in config, so lets move clock by 5 seconds self.clock.advance(5) def check_config(config): self.assertTrue(not config._save_timer.active()) del config config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir) self.assertEqual(config['string'], 'baz') self.assertEqual(config['int'], 2) check_config(config)
def check_config(): config = Config("test.conf", config_dir=self.config_dir) self.assertEquals(config["string"], "foobar") self.assertEquals(config["float"], 0.435)
#!/usr/bin/python2 import os import sys import logging # add logging handler to silence logging errors from deluge module logging.getLogger('deluge').addHandler(logging.NullHandler()) # import deluge configuration module from deluge.config import Config # define filename and paths this_script = os.path.basename(__file__) deluge_core_conf_file = "/config/core.conf" core_conf = Config(deluge_core_conf_file) # read in command line arguments vpn_ip = sys.argv[1] # attempt to read in config file if os.path.exists(deluge_core_conf_file): try: core_conf['listen_interface'] except KeyError: print "[warn] Deluge config file %s does not contain valid data, exiting Python script %s..." % ( deluge_core_conf_file, this_script)
#!/usr/bin/env python $ from deluge.config import Config import hashlib import os.path import sys if len(sys.argv) == 2: deluge_dir = os.path.expanduser(sys.argv[1]) if os.path.isdir(deluge_dir): try: config = Config("web.conf", config_dir=deluge_dir) except IOError, e: print "Can't open web ui config file: ", e else: from itertools import islice with open ("/root/pass.txt", "r") as myfile: password=myfile.read().replace('\n', '') s = hashlib.sha1() s.update(config['pwd_salt']) s.update(password) config['pwd_sha1'] = s.hexdigest() try: config.save() except IOError, e: print "Couldn't save new password: "******"New password successfully set!" else: print "%s is not a directory!" % deluge_dir
def check_config(): config = Config('test.conf', config_dir=self.config_dir) self.assertEqual(config['string'], 'foobar') self.assertEqual(config['float'], 0.435)
class HostList(object): """This class contains methods for adding, removing and looking up hosts in hostlist.conf.""" def __init__(self): migrate_hostlist('hostlist.conf.1.2', 'hostlist.conf') self.config = Config( 'hostlist.conf', default_hostlist(), config_dir=get_config_dir(), file_version=3, ) self.config.run_converter((1, 2), 3, migrate_config_2_to_3) self.config.save() def check_info_exists(self, hostname, port, username, skip_host_id=None): """Check for existing host entries with the same details. Args: hostname (str): The IP or hostname of the deluge daemon. port (int): The port of the deluge daemon. username (str): The username to login to the daemon with. skip_host_id (str): A host_id to skip to check if other hosts match details. Raises: ValueError: Host details already exist. """ for host_entry in self.config['hosts']: if (hostname, port, username) == ( host_entry[1], host_entry[2], host_entry[3], ): if skip_host_id is not None and skip_host_id == host_entry[0]: continue raise ValueError('Host details already in hostlist') def add_host(self, hostname, port, username, password): """Add a new host to hostlist. Args: hostname (str): The IP or hostname of the deluge daemon. port (int): The port of the deluge daemon. username (str): The username to login to the daemon with. password (str): The password to login to the daemon with. Returns: str: The new host id. """ if (not password and not username or username == 'localclient') and hostname in LOCALHOST: username, password = get_localhost_auth() validate_host_info(hostname, port) self.check_info_exists(hostname, port, username) host_id = uuid.uuid4().hex self.config['hosts'].append( (host_id, hostname, port, username, password)) self.config.save() return host_id def get_host_info(self, host_id): """Get the host details for host_id. Args: host_id (str): The host id to get info on. Returns: list: A list of (host_id, hostname, port, username). """ for host_entry in self.config['hosts']: if host_entry[0] == host_id: return host_entry[0:4] else: return [] def get_hosts_info(self): """Get information of all the hosts in the hostlist. Returns: list of lists: Host information in the format [(host_id, hostname, port, username)]. """ return [host_entry[0:4] for host_entry in self.config['hosts']] def get_host_status(self, host_id): """Gets the current status (online/offline) of the host Args: host_id (str): The host id to check status of. Returns: tuple: A tuple of strings (host_id, status, version). """ status_offline = (host_id, 'Offline', '') def on_connect(result, c, host_id): """Successfully connected to a daemon""" def on_info(info, c): c.disconnect() return host_id, 'Online', info def on_info_fail(reason, c): c.disconnect() return status_offline return c.daemon.info().addCallback(on_info, c).addErrback(on_info_fail, c) def on_connect_failed(reason, host_id): """Connection to daemon failed""" log.debug('Host status failed for %s: %s', host_id, reason) return status_offline try: host_id, host, port, user = self.get_host_info(host_id) except ValueError: log.warning('Problem getting host_id info from hostlist') return defer.succeed(status_offline) try: ip = gethostbyname(host) except gaierror as ex: log.error('Error resolving host %s to ip: %s', host, ex.args[1]) return defer.succeed(status_offline) host_conn_info = ( ip, port, 'localclient' if not user and host in LOCALHOST else user, ) if client.connected() and host_conn_info == client.connection_info(): # Currently connected to host_id daemon. def on_info(info, host_id): log.debug('Client connected, query info: %s', info) return host_id, 'Connected', info return client.daemon.info().addCallback(on_info, host_id) else: # Attempt to connect to daemon with host_id details. c = Client() d = c.connect(host, port, skip_authentication=True) d.addCallback(on_connect, c, host_id) d.addErrback(on_connect_failed, host_id) return d def update_host(self, host_id, hostname, port, username, password): """Update the supplied host id with new connection details. Args: host_id (str): The host id to update. hostname (str): The new IP or hostname of the deluge daemon. port (int): The new port of the deluge daemon. username (str): The new username to login to the daemon with. password (str): The new password to login to the daemon with. """ validate_host_info(hostname, port) self.check_info_exists(hostname, port, username, skip_host_id=host_id) if (not password and not username or username == 'localclient') and hostname in LOCALHOST: username, password = get_localhost_auth() for idx, host_entry in enumerate(self.config['hosts']): if host_id == host_entry[0]: self.config['hosts'][ idx] = host_id, hostname, port, username, password self.config.save() return True return False def remove_host(self, host_id): """Removes the host entry from hostlist config. Args: host_id (str): The host id to remove. Returns: bool: True is successfully removed, False otherwise. """ for host_entry in self.config['hosts']: if host_id == host_entry[0]: self.config['hosts'].remove(host_entry) self.config.save() return True else: return False def add_default_host(self): self.add_host(DEFAULT_HOST, DEFAULT_PORT, *get_localhost_auth()) def connect_host(self, host_id): """Connect to host daemon""" for host_entry in self.config['hosts']: if host_entry[0] == host_id: __, host, port, username, password = host_entry return client.connect(host, port, username, password) return defer.fail(Exception('Bad host id'))
#!/usr/bin/env python3 from os import getenv from deluge.config import Config from deluge.core.preferencesmanager import DEFAULT_PREFS conf = Config('core.conf', DEFAULT_PREFS, getenv('DELUGE_CONFIG_DIR')) # Folders data_dir = getenv('DELUGE_DATA_DIR') if not data_dir: print("Deluge data directory couldn't find.") path_map = { 'autoadd_location': 'autoadd', 'download_location': 'download', 'move_completed_path': 'completed', 'torrentfiles_location': 'torrentfiles' } for key, val in path_map.items(): conf.set_item(key, "/".join([data_dir, val])) # Listening Ports l_port_begin = getenv('DELUGE_PORT_BEGIN') if l_port_begin: l_port_end = getenv('DELUGE_PORT_END') conf.set_item('listen_ports', [l_port_begin, l_port_end or l_port_begin]) conf.set_item('random_port', False) # Allow Remote conf.set_item('allow_remote', True)
from deluge.config import Config # define filename and paths this_script = os.path.basename(__file__) # read in command line arguments for key deluge_conf_path = sys.argv[1] # read in command line arguments for key key = sys.argv[2] # read in command line argument for value value = sys.argv[3] # parse file core_conf = Config(deluge_conf_path) # attempt to read in config file if os.path.exists(deluge_conf_path): try: core_conf[key] except KeyError: print("[warn] Deluge config file %s does not contain valid data, exiting Python script %s..." % (deluge_conf_path, this_script)) sys.exit(1) if core_conf[key] != "":
#!/usr/bin/python2 import os import sys import logging # add logging handler to silence logging errors from deluge module logging.getLogger('deluge').addHandler(logging.NullHandler()) # import deluge configuration module from deluge.config import Config # define filename and paths this_script = os.path.basename(__file__) deluge_core_conf_file = "/config/core.conf" core_conf = Config(deluge_core_conf_file) # read in command line arguments vpn_ip = sys.argv[1] # attempt to read in config file if os.path.exists(deluge_core_conf_file): try: core_conf['listen_interface'] except KeyError: print "[warn] Deluge config file %s does not contain valid data, exiting Python script %s..." % (deluge_core_conf_file, this_script) sys.exit(1)
### COPY AFTER THIS LINE ### # Changes the password for Deluge's Web UI from deluge.config import Config import hashlib import os.path import sys if len(sys.argv) == 2: deluge_dir = os.path.expanduser(sys.argv[1]) if os.path.isdir(deluge_dir): try: config = Config("web.conf", config_dir=deluge_dir) except IOError, e: print "Can't open web ui config file: ", e else: password = raw_input("Enter new password: "******"Couldn't save new password: "******"New password successfully set!" else:
from deluge.core.preferencesmanager import DEFAULT_PREFS as CORE_CONFIG_DEFAULTS envNamePrefix = "DELUGE_CONF_CORE_" configDir = '/home/deluge/.config/deluge' configFileName = 'core.conf' configPath = configDir + '/' + configFileName if os.path.isfile(configPath): logging.info("Config file (%s) found, skipping defaults" % configPath) defaults = None else: logging.info("Config file (%s) not found, loading defaults" % configPath) defaults = CORE_CONFIG_DEFAULTS logging.info("Reading %s" % configFileName) config = Config(configFileName, defaults, configDir) for param in os.environ.keys(): if param.startswith(envNamePrefix): propertyName = param[len(envNamePrefix):].lower() propertyValue = os.environ[param] if propertyValue.lower() in ("true", "yes"): propertyValue = True elif propertyValue.lower() in ("false", "no"): propertyValue = False elif re.match(r'^\[.*\]$', propertyValue): propertyValue = propertyValue[1:-1].split(',') logging.debug("Injecting %s = %s" % (propertyName, propertyValue)) config[propertyName] = propertyValue
def get_env_or_default(var, default): v = os.environ.get(var) if v: return v else: return default config_dir = get_env_or_default('CONFIG_DIR', '/config') web_port = int(get_env_or_default('WEB_PORT', 8112)) password = get_env_or_default('DELUGE_PASSWORD', 'deluge') daemon_port = int(get_env_or_default('DAEMON_PORT', 58846)) config = Config("web.conf", config_dir=config_dir) config['default_daemon'] = '127.0.0.1:%d' % daemon_port config['port'] = web_port salt = hashlib.sha1(str(random.getrandbits(40))).hexdigest() s = hashlib.sha1(salt) config['pwd_salt'] = salt s.update(password) config['pwd_sha1'] = s.hexdigest() try: config.save() except IOError, e: print "Couldn't save new password: ", e