If network config is empty we create a sample config
164634
def _create_network_config(self):
        
        path = os.path.join(self.working_dir, "etc", "network")
        os.makedirs(path, exist_ok=True)
        open(os.path.join(path, ".gns3_perms"), 'a').close()
        os.makedirs(os.path.join(path, "if-up.d"), exist_ok=True)
        os.makedirs(os.path.join(path, "if-down.d"), exist_ok=True)
        os.makedirs(os.path.join(path, "if-pre-up.d"), exist_ok=True)
        os.makedirs(os.path.join(path, "if-post-down.d"), exist_ok=True)

        if not os.path.exists(os.path.join(path, "interfaces")):
            with open(os.path.join(path, "interfaces"), "w+") as f:
                f.write("""#
# This is a sample network config uncomment lines to configure the network
#

""")
                for adapter in range(0, self.adapters):
                    f.write("""
# Static config for eth{adapter}
#auto eth{adapter}
#iface eth{adapter} inet static
#\taddress 192.168.{adapter}.2
#\tnetmask 255.255.255.0
#\tgateway 192.168.{adapter}.1
#\tup echo nameserver 192.168.{adapter}.1 > /etc/resolv.conf

# DHCP config for eth{adapter}
# auto eth{adapter}
# iface eth{adapter} inet dhcp""".format(adapter=adapter))
        return path
880316
function verifyConfig(config) {
  var i = 0;
  var required = ['logs', 'client_name', 'server_port'];
  var optional = {
    'server_host': '127.0.0.1'
  };

  for(i = 0; i < required.lenght; i++) {
    if(!config[required[i]]) {
      throw 'Config missing required: ' + required[i];
    }
  }

  for(i in optional) {
    if(optional.hasOwnProperty(i)) {
      if(!config[i]) {
        config[i] = optional[i];
      }
    }
  }

  return config;
}
503222
def system(name, **kwargs):
    '''
    

    '''
    ret = {
        'name': name,
        'changes': {},
        'result': True,
        'comment': 'Global network settings are up to date.',
    }
    apply_net_settings = False
    kwargs['test'] = __opts__['test']
    # Build global network settings
    try:
        old = __salt__['ip.get_network_settings']()
        new = __salt__['ip.build_network_settings'](**kwargs)
        if __opts__['test']:
            if old == new:
                return ret
            if not old and new:
                ret['result'] = None
                ret['comment'] = 'Global network settings are set to be added.'
                return ret
            elif old != new:
                diff = difflib.unified_diff(old, new, lineterm='')
                ret['result'] = None
                ret['comment'] = 'Global network settings are set to be ' \
                                 'updated:\n{0}'.format('\n'.join(diff))
                return ret
        if not old and new:
            apply_net_settings = True
            ret['changes']['network_settings'] = 'Added global network settings.'
        elif old != new:
            diff = difflib.unified_diff(old, new, lineterm='')
            apply_net_settings = True
            ret['changes']['network_settings'] = '\n'.join(diff)
    except AttributeError as error:
        ret['result'] = False
        ret['comment'] = six.text_type(error)
        return ret
    except KeyError as error:
        ret['result'] = False
        ret['comment'] = six.text_type(error)
        return ret

    # Apply global network settings
    if apply_net_settings:
        try:
            __salt__['ip.apply_network_settings'](**kwargs)
        except AttributeError as error:
            ret['result'] = False
            ret['comment'] = six.text_type(error)
            return ret

    return ret
335835
def validate_config(cls, config):
        
        if "config_file" not in config:
            raise ValueError("No config file path given")
        if "socket_file" not in config:
            raise ValueError("No control socket path given")
        if "pid_file" not in config:
            raise ValueError("No PID file path given")
        if "stats" in config and "port" not in config["stats"]:
            raise ValueError("Stats interface defined, but no port given")
        if "proxies" in config:
            cls.validate_proxies_config(config["proxies"])

        return config
18827
def FinalizeConfigInit(config,
                       token,
                       admin_password = None,
                       redownload_templates = False,
                       repack_templates = True,
                       prompt = True):
  """"""
  config.Set("Server.initialized", True)
  print("\nWriting configuration to %s." % config["Config.writeback"])
  config.Write()
  print("Initializing the datastore.")
  # Reload the config and initialize the GRR database.
  server_startup.Init()

  print("\nStep 3: Adding GRR Admin User")
  try:
    CreateUser("admin", password=admin_password, is_admin=True)
  except UserAlreadyExistsError:
    if prompt:
      # pytype: disable=wrong-arg-count
      if ((builtins.input("User 'admin' already exists, do you want to "
                          "reset the password? [yN]: ").upper() or "N") == "Y"):
        UpdateUser("admin", password=admin_password, is_admin=True)
      # pytype: enable=wrong-arg-count
    else:
      UpdateUser("admin", password=admin_password, is_admin=True)

  print("\nStep 4: Repackaging clients with new configuration.")
  if prompt:
    redownload_templates = RetryBoolQuestion(
        "Server debs include client templates. Re-download templates?", False)
    repack_templates = RetryBoolQuestion("Repack client templates?", True)
  if redownload_templates:
    InstallTemplatePackage()
  # Build debug binaries, then build release binaries.
  if repack_templates:
    repacking.TemplateRepacker().RepackAllTemplates(upload=True, token=token)
  print("\nGRR Initialization complete! You can edit the new configuration "
        "in %s.\n" % config["Config.writeback"])
  print("Please restart the service for the new configuration to take "
        "effect.\n")
1017783
def create_config_files(directory):
    
    # get the config file template
    template_url = ("https://securenetconnection.com/vpnconfig/"
                    "openvpn-template.ovpn")
    resp = requests.get(template_url)
    resp.raise_for_status()
    template = resp.content

    # get the available servers and create a config file for each server
    server_url = ("https://securenetconnection.com/vpnconfig/"
                  "servers-cli.php")
    resp = requests.get(server_url)
    resp.raise_for_status()
    servers = resp.content.split("\n")

    if not os.path.exists(directory):
        os.makedirs(directory)
    with open(os.path.join(directory, "servers.txt"), 'w') as f:
        f.write(resp.content)

    for server_line in servers:
        if server_line.strip() == "":
            continue
        server_line = server_line.split("|")
        try:
            ip, desc, country, udp_sup, tcp_sup = server_line
        except ValueError:
            ip, desc, country, udp_sup, tcp_sup, no_rand = server_line
        with open(os.path.join(directory, ip + ".ovpn"), 'w') as file_o:
            file_o.write(template)
            # create tcp if available, else udp
            tcp_sup = tcp_sup.strip()
            if tcp_sup:
                port, proto = 443, "tcp"
            else:
                port, proto = 53, "udp"
            file_o.write("remote {0} {1}\n".format(ip, port))
            file_o.write("proto {0}\n".format(proto))
            # add automatic dns server update
            file_o.write("up /etc/openvpn/update-resolv-conf\n")
            file_o.write("down /etc/openvpn/update-resolv-conf\n")
896943
async def restore_networking_configuration(self):
        
        self._data = await self._handler.restore_networking_configuration(
            system_id=self.system_id)
1324835
def reset_config(ip, mac):
    """"""
    click.echo("Reset configuration of button %s..." % ip)
    data = {
        'single': "",
        'double': "",
        'long': "",
        'touch': "",
    }
    request = requests.post(
        'http://{}/{}/{}/'.format(ip, URI, mac), data=data, timeout=TIMEOUT)

    if request.status_code == 200:
        click.echo("Reset configuration of %s" % mac)
733063
def ensure_local_net(
        network_name: str = DOCKER_STARCRAFT_NETWORK,
        subnet_cidr: str = SUBNET_CIDR
) -> None:
    
    logger.info(f"checking whether docker has network {network_name}")
    ipam_pool = docker.types.IPAMPool(subnet=subnet_cidr)
    ipam_config = docker.types.IPAMConfig(pool_configs=[ipam_pool])
    networks = docker_client.networks.list(names=DOCKER_STARCRAFT_NETWORK)
    output = networks[0].short_id if networks else None
    if not output:
        logger.info("network not found, creating ...")
        output = docker_client.networks.create(DOCKER_STARCRAFT_NETWORK, ipam=ipam_config).short_id
    logger.debug(f"docker network id: {output}")
587311
def build_network_settings(**settings):
    '''
    
    '''
    changes = []

    # Read current configuration and store default values
    current_network_settings = _parse_current_network_settings()

    # Build settings
    opts = _parse_network_settings(settings, current_network_settings)

    # Ubuntu has moved away from /etc/default/networking
    # beginning with the 12.04 release so we disable or enable
    # the networking related services on boot
    skip_etc_default_networking = (
        __grains__['osfullname'] == 'Ubuntu' and
        int(__grains__['osrelease'].split('.')[0]) >= 12)
    if skip_etc_default_networking:
        if opts['networking'] == 'yes':
            service_cmd = 'service.enable'
        else:
            service_cmd = 'service.disable'

        if __salt__['service.available']('NetworkManager'):
            __salt__[service_cmd]('NetworkManager')

        if __salt__['service.available']('networking'):
            __salt__[service_cmd]('networking')
    else:
        try:
            template = JINJA.get_template('network.jinja')
        except jinja2.exceptions.TemplateNotFound:
            log.error('Could not load template network.jinja')
            return ''
        network = template.render(opts)

        if 'test' in settings and settings['test']:
            return _read_temp(network)
        # Write settings
        _write_file_network(network, _DEB_NETWORKING_FILE, True)

    # Get hostname and domain from opts
    sline = opts['hostname'].split('.', 1)
    opts['hostname'] = sline[0]
    current_domainname = current_network_settings['domainname']
    current_searchdomain = current_network_settings['searchdomain']

    new_domain = False
    if len(sline) > 1:
        new_domainname = sline[1]
        if new_domainname != current_domainname:
            domainname = new_domainname
            opts['domainname'] = new_domainname
            new_domain = True
        else:
            domainname = current_domainname
            opts['domainname'] = domainname
    else:
        domainname = current_domainname
        opts['domainname'] = domainname

    new_search = False
    if 'search' in opts:
        new_searchdomain = opts['search']
        if new_searchdomain != current_searchdomain:
            searchdomain = new_searchdomain
            opts['searchdomain'] = new_searchdomain
            new_search = True
        else:
            searchdomain = current_searchdomain
            opts['searchdomain'] = searchdomain
    else:
        searchdomain = current_searchdomain
        opts['searchdomain'] = searchdomain

    # If the domain changes, then we should write the resolv.conf file.
    if new_domain or new_search:
        # Look for existing domain line and update if necessary
        resolve = _parse_resolve()
        domain_prog = re.compile(r'domain\s+')
        search_prog = re.compile(r'search\s+')
        new_contents = []

        for item in _read_file(_DEB_RESOLV_FILE):
            if domain_prog.match(item):
                item = 'domain {0}'.format(domainname)
            elif search_prog.match(item):
                item = 'search {0}'.format(searchdomain)
            new_contents.append(item)

        # A domain line didn't exist so we'll add one in
        # with the new domainname
        if 'domain' not in resolve:
            new_contents.insert(0, 'domain {0}' . format(domainname))

        # A search line didn't exist so we'll add one in
        # with the new search domain
        if 'search' not in resolve:
            new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain))

        new_resolv = '\n'.join(new_contents)

        # Write /etc/resolv.conf
        if not ('test' in settings and settings['test']):
            _write_file_network(new_resolv, _DEB_RESOLV_FILE)

    #  used for returning the results back
    try:
        template = JINJA.get_template('display-network.jinja')
    except jinja2.exceptions.TemplateNotFound:
        log.error('Could not load template display-network.jinja')
        return ''
    network = template.render(opts)
    changes.extend(_read_temp(network))

    return changes
1169857
def network_create(self, name, **kwargs):
        '''
        
        '''
        nt_ks = self.compute_conn
        kwargs['label'] = name
        kwargs = self._sanatize_network_params(kwargs)
        net = nt_ks.networks.create(**kwargs)
        return net.__dict__
1131901
def initialize_network(neutron):
    
    body_sample = {
        "network": {
            "name": 'provision_bob',
            "admin_state_up": True,
        }
    }
    netw = neutron.create_network(body=body_sample)['network']
    body_create_subnet = {
        'subnets': [{
            'name': 'rdo-m-subnet',
            'cidr': '192.0.2.0/24',
            'ip_version': 4,
            'network_id': netw['id'],
            'host_routes': [{
                'destination': '169.254.169.254/32',
                'nexthop': '192.0.2.240'
            }],
            'gateway_ip': '192.0.2.1',
            'dns_nameservers': ['8.8.8.8', '8.8.4.4'],
            'allocation_pools': [{'start': '192.0.2.30', 'end': '192.0.2.199'}]}]}
    response = neutron.create_subnet(body=body_create_subnet)
    subnet_id = response['subnets'][0]['id']
    router = neutron.list_routers(name='router').get('routers')[0]
    response = neutron.add_interface_router(router['id'], {'subnet_id': subnet_id})
387378
private function checkConfig()
    {
        if (empty($this->config['api_key'])) {
            throw new Exception("`api_key' must be configured");
        }

        if (empty($this->config['host'])) {
            throw new Exception("`host' must be configured");
        }

        if (empty($this->config['port'])) {
            $this->config['port'] = !empty($this->config['secure']) ? 443 : 80;
        }

        if (!isset($this->config['secure'])) {
            $this->config['secure'] = ($this->config['port'] == 443);
        }

        if (empty($this->config['hostname'])) {
            $this->config['hostname'] = gethostname() ? gethostname() : '<unknown>';
        }

        if (empty($this->config['project_root'])) {
            $this->config['project_root'] = dirname(__FILE__);
        }

        if (empty($this->config['environment_name'])) {
            $this->config['environment_name'] = 'development';
        }

        if (!isset($this->config['params_filters'])) {
            $this->config['params_filters'] = array('/password/');
        }

        if (!isset($this->config['connect_timeout'])) {
            $this->config['connect_timeout'] = 3;
        }

        if (!isset($this->config['write_timeout'])) {
            $this->config['write_timeout'] = 3;
        }

        if (!isset($this->config['backtrace_filters'])) {
            $this->config['backtrace_filters'] = array(
                sprintf('/^%s/', preg_quote($this->config['project_root'], '/')) => '[PROJECT_ROOT]'
            );
        }

        if (!isset($this->config['skipped_exceptions'])) {
            $this->config['skipped_exceptions'] = array();
        }

        if (!isset($this->config['default_writer'])) {
            $this->config['default_writer'] = 'Errbit\Writer\SocketWriter';
        }

        if (!isset($this->config['agent'])) {
            $this->config['agent'] = 'errbitPHP';
        }
        if (!isset($this->config['async'])) {
            $this->config['async'] = false;
        }
        if (!isset($this->config['ignore_user_agent'])) {
            $this->config['ignore_user_agent'] = array();
        }
    }
597287
def autoconf(self):
        
        nginxInfo = NginxInfo(self._host, self._port,
                                self._user, self._password, 
                                self._statuspath, self._ssl)
        return nginxInfo is not None
983715
def Initialize(config=None,
               external_hostname = None,
               admin_password = None,
               redownload_templates = False,
               repack_templates = True,
               token = None):
  """"""

  print("Checking write access on config %s" % config["Config.writeback"])
  if not os.access(config.parser.filename, os.W_OK):
    raise IOError("Config not writeable (need sudo?)")

  print("\nStep 0: Importing Configuration from previous installation.")
  options_imported = 0
  prev_config_file = config.Get("ConfigUpdater.old_config", default=None)
  if prev_config_file and os.access(prev_config_file, os.R_OK):
    print("Found config file %s." % prev_config_file)
    # pytype: disable=wrong-arg-count
    if builtins.input("Do you want to import this configuration? "
                      "[yN]: ").upper() == "Y":
      options_imported = ImportConfig(prev_config_file, config)
    # pytype: enable=wrong-arg-count
  else:
    print("No old config file found.")

  print("\nStep 1: Setting Basic Configuration Parameters")
  print("We are now going to configure the server using a bunch of questions.")
  ConfigureDatastore(config)
  ConfigureUrls(config, external_hostname=external_hostname)
  ConfigureEmails(config)

  print("\nStep 2: Key Generation")
  if config.Get("PrivateKeys.server_key", default=None):
    if options_imported > 0:
      print("Since you have imported keys from another installation in the "
            "last step,\nyou probably do not want to generate new keys now.")
    # pytype: disable=wrong-arg-count
    if (builtins.input("You already have keys in your config, do you want to"
                       " overwrite them? [yN]: ").upper() or "N") == "Y":
      config_updater_keys_util.GenerateKeys(config, overwrite_keys=True)
    # pytype: enable=wrong-arg-count
  else:
    config_updater_keys_util.GenerateKeys(config)

  FinalizeConfigInit(
      config,
      token,
      admin_password=admin_password,
      redownload_templates=redownload_templates,
      repack_templates=repack_templates,
      prompt=True)
671223
def create_network(self, name, admin_state_up=True, router_ext=None, network_type=None, physical_network=None, segmentation_id=None, shared=None, vlan_transparent=None):
        '''
        
        '''
        body = {'name': name,
                'admin_state_up': admin_state_up}
        if router_ext:
            body['router:external'] = router_ext
        if network_type:
            body['provider:network_type'] = network_type
        if physical_network:
            body['provider:physical_network'] = physical_network
        if segmentation_id:
            body['provider:segmentation_id'] = segmentation_id
        if shared:
            body['shared'] = shared
        if vlan_transparent:
            body['vlan_transparent'] = vlan_transparent
        return self.network_conn.create_network(body={'network': body})
1016854
def do_create(config, config_dir):
    
    if os.path.exists(config_dir):
        print "Configuration '{}' already exists.".format(config)
        exit(1)
    os.makedirs(config_dir)
    print "Configuration directory created."

    url = raw_input("RSS URL for processing []: ")
    torrent_dir = raw_input("Output directory for found .torrent files [{}]: "\
        .format(DEFAULT_TORRRENT_DIR)) or DEFAULT_TORRRENT_DIR
    update_interval = raw_input("Update interval (mins) [{}]: "\
        .format(DEFAULT_UPDATE_INTERVAL)) or DEFAULT_UPDATE_INTERVAL

    editor = os.environ["EDITOR"]

    config_filter = os.path.join(config_dir, 'filter')
    if confirm("Do you want to create filters list?", False):
        call([editor, config_filter])
        print "Filter configuration has been saved."

    config_blacklist = os.path.join(config_dir, 'blacklist')
    if confirm("Do you want to create blacklist?", False):
        call([editor, config_filter])
        print "Blacklist configuration has been saved."

    config_file = os.path.join(config_dir, 'config')
    config_data = json.dumps({
        "url": url,
        "torrent_dir": torrent_dir,
        "update_interval": update_interval
    }, sort_keys=True, indent=4, separators=(',', ': '))
    with open(config_file, 'w') as f:
        f.write(config_data)

    ct = CronTab(user=True)
    cmd = "{} {} -e {}".format(sys.executable,
                               os.path.abspath(__file__),
                               config)
    job = ct.new(command=cmd)
    job.minute.every(update_interval)
    job.enable()
    ct.write()
    print "Crontab updated."

    print "Config '{}' has been saved.".format(config)