示例#1
0
    def ifdown(self, reset=False):
        logger.info('Bringing down interface %s', self.name)
        ret = True
        try:
            sh.ifdown(self.name)
        except:
            logger.warning('Error Bringing down interface %s', self.name)
            ret = False

        if reset:
            logger.warning('Resetting interface %s', self.name)
            for i in ['0.0.0.0/0', 'down']:
                try:
                    sh.ifconfig(self.name, i)
                except:
                    pass

        return ret
示例#2
0
def configure_ethernet_device(device):
    form = EthernetConfigureForm()
    device_map = None

    if os.access(NETWORK_FILE, os.W_OK):
        device_map = _parse_network_file()
    else:
        flash(NETWORK_FILE + ' is not writable!', 'error')
        return redirect(url_for('settings.host'))

    properties = _get_ethernet_properties(device, device_map)
    addresses = netifaces.ifaddresses(device)
    ipv4 = addresses[netifaces.AF_INET]

    #first address and gateway
    ip_address = ipv4[0]['addr']
    subnet_mask = ipv4[0]['netmask']
    gateways = netifaces.gateways()
    gateway = gateways['default'][netifaces.AF_INET]
    default_gateway = gateway[0]

    if not form.is_submitted():
        form.ip_address.data = ip_address
        form.gateway.data = default_gateway
        form.netmask.data = subnet_mask

        if not properties:
            if device == 'lo' or device == 'lo0':
                flash('Unable to configure loopback device!', 'error')
                return redirect(url_for('settings.host'))

            flash(
                'Device ' + device + ' not found in ' + NETWORK_FILE +
                ' you should use your OS tools to configure your network.',
                'error')
            return redirect(url_for('settings.host'))
        else:
            for s in properties:
                if 'loopback' in s:
                    flash('Unable to configure loopback device!', 'error')
                    return redirect(url_for('settings.host'))
                if 'static' in s:
                    form.connection_type.data = 'static'
                if 'dhcp' in s:
                    form.connection_type.data = 'dhcp'

    if form.validate_on_submit():
        if form.connection_type.data == 'static':
            i = 0
            interface_index = 0

            #find our iface definition string for "device"
            for i in range(0, len(properties)):
                if properties[i].find("dhcp") != -1 and properties[i].find(
                        device) != -1:
                    interface_index = device_map.index(properties[i])
                    x = properties[i].replace('dhcp', 'static')
                    #replace dhcp with static, remove original add copy
                    del properties[i]
                    #delete our interface from the map, add it to new properties list for re-adding to map later
                    del device_map[interface_index]
                    properties.append(x)
                    break
                else:
                    if properties[i].find("static") != -1 and properties[
                            i].find(device) != -1:
                        interface_index = device_map.index(properties[i])
                        truncated = properties[i].splitlines()
                        #truncate off address/netmask/gateway, we add after
                        del properties[i]
                        #if we're static but we just want to change our address
                        del device_map[interface_index]
                        properties.append(truncated[0] + "\n")
                        break

            for i in range(0, len(device_map)):
                if device_map[i].find("auto " + device) != -1:
                    del device_map[i]
                    break

            #append address values to interface string
            address = str("\taddress " + form.ip_address.data + "\n")
            netmask = str("\tnetmask " + form.netmask.data + "\n")
            gateway = str("\tgateway " + form.gateway.data + "\n")

            properties.append(address)
            properties.append(netmask)
            properties.append(gateway)

            #append new interface string with address information included
            for i in range(0, len(properties)):
                device_map.insert(interface_index + i, properties[i])

            #write the network file with the new device map
            for i in range(0, len(device_map)):
                if device_map[i].find("iface default inet dhcp") != -1:
                    x = device_map[i].replace('dhcp', 'static')
                    del device_map[i]
                    device_map.append(x)
                    break

            _write_network_file(device_map)
        else:
            for i in range(0, len(properties)):
                if properties[i].find("static") != -1 and properties[i].find(
                        device) != -1:
                    interface_index = device_map.index(properties[i])
                    truncated = properties[0].splitlines()
                    x = truncated[0].replace('static', 'dhcp')

                    del properties
                    properties = []
                    properties.append("auto " + device + "\n" + x + "\n")

                    del device_map[interface_index]
                    for i in range(0, len(properties)):
                        device_map.insert(interface_index + i, properties[i])

            for i in range(0, len(device_map)):
                if device_map[i].find("iface default inet static") != -1:
                    x = device_map[i].replace('static', 'dhcp')
                    del device_map[i]
                    device_map.append(x)
                    break

            _write_network_file(device_map)


#substitute values in the device_map, write the file and restart networking
        with sh.sudo:
            try:
                sh.ifdown(str(device))
            except sh.ErrorReturnCode_1:
                flash('Unable to restart networking. Please try manually.',
                      'error')
            try:
                sh.ifup(str(device))
            except sh.ErrorReturnCode_1:
                flash('Unable to restart networking.  Please try manually.',
                      'error')

        form.ethernet_device.data = device

    form.ethernet_device.data = device

    return render_template('settings/configure_ethernet_device.html',
                           form=form,
                           device=device,
                           active="network settings")
示例#3
0
def configure_ethernet_device(device):
    form = EthernetConfigureForm()
    device_map = None

    if os.access(NETWORK_FILE, os.W_OK):
        device_map = _parse_network_file()
    else:
        flash(NETWORK_FILE + ' is not writable!', 'error')
        return redirect(url_for('settings.host'))

    properties = _get_ethernet_properties(device, device_map)
    addresses = netifaces.ifaddresses(device)
    ipv4 = addresses[netifaces.AF_INET]

#first address and gateway
    ip_address = ipv4[0]['addr']
    subnet_mask = ipv4[0]['netmask']
    gateways = netifaces.gateways()
    gateway = gateways['default'][netifaces.AF_INET]
    default_gateway = gateway[0]

    if not form.is_submitted():
        form.ip_address.data = ip_address
        form.gateway.data = default_gateway
        form.netmask.data = subnet_mask

        if not properties:
            if device == 'lo' or device == 'lo0':
                flash('Unable to configure loopback device!', 'error')
                return redirect(url_for('settings.host'))

            flash('Device ' + device + ' not found in ' + NETWORK_FILE + ' you should use your OS tools to configure your network.', 'error')
            return redirect(url_for('settings.host'))
        else:
            for s in properties:
                if 'loopback' in s:
                    flash('Unable to configure loopback device!', 'error')
                    return redirect(url_for('settings.host'))
                if 'static' in s:
                    form.connection_type.data = 'static'
                if 'dhcp' in s:
                    form.connection_type.data = 'dhcp'

    if form.validate_on_submit():
        if form.connection_type.data == 'static':
            i = 0
            interface_index = 0

#find our iface definition string for "device"
            for i in range(0, len(properties)):
                if properties[i].find("dhcp") != -1 and properties[i].find(device) != -1:
                    interface_index = device_map.index(properties[i])
                    x = properties[i].replace('dhcp', 'static')
                    #replace dhcp with static, remove original add copy
                    del properties[i]
#delete our interface from the map, add it to new properties list for re-adding to map later
                    del device_map[interface_index]
                    properties.append(x)
                    break
                else:
                    if properties[i].find("static") != -1 and properties[i].find(device) != -1:
                        interface_index = device_map.index(properties[i])
                        truncated = properties[i].splitlines()
                        #truncate off address/netmask/gateway, we add after
                        del properties[i]
#if we're static but we just want to change our address
                        del device_map[interface_index]
                        properties.append(truncated[0] + "\n")
                        break

            for i in range(0, len(device_map)):
                if device_map[i].find("auto " + device) != -1:
                    del device_map[i]
                    break

            #append address values to interface string
            address = str("\taddress " + form.ip_address.data + "\n")
            netmask = str("\tnetmask " + form.netmask.data + "\n")
            gateway = str("\tgateway " + form.gateway.data + "\n")

            properties.append(address)
            properties.append(netmask)
            properties.append(gateway)

            #append new interface string with address information included
            for i in range(0, len(properties)):
                device_map.insert(interface_index + i, properties[i])

            #write the network file with the new device map
            for i in range(0, len(device_map)):
                if device_map[i].find("iface default inet dhcp") != -1:
                    x = device_map[i].replace('dhcp', 'static')
                    del device_map[i]
                    device_map.append(x)
                    break

            _write_network_file(device_map);
        else:
            for i in range(0, len(properties)):
                if properties[i].find("static") != -1 and properties[i].find(device) != -1:
                    interface_index = device_map.index(properties[i])
                    truncated = properties[0].splitlines()
                    x = truncated[0].replace('static', 'dhcp')

                    del properties
                    properties = []
                    properties.append("auto " + device + "\n" + x + "\n")
            
                    del device_map[interface_index]
                    for i in range(0, len(properties)):
                        device_map.insert(interface_index + i, properties[i])

            for i in range(0, len(device_map)):
                if device_map[i].find("iface default inet static") != -1:
                    x = device_map[i].replace('static', 'dhcp')
                    del device_map[i]
                    device_map.append(x)
                    break

            _write_network_file(device_map)
#substitute values in the device_map, write the file and restart networking
        with sh.sudo:
            try:
                sh.ifdown(str(device))
            except sh.ErrorReturnCode_1:
                flash('Unable to restart networking. Please try manually.', 'error')
            try:
                sh.ifup(str(device))
            except sh.ErrorReturnCode_1:
                flash('Unable to restart networking.  Please try manually.', 'error')

        form.ethernet_device.data = device

    form.ethernet_device.data = device

    return render_template('settings/configure_ethernet_device.html', form=form, device=device, active="network settings")
示例#4
0
def setup_networking(ob_num: int):
    """Sets up networking.

    Installs some debs manually that are required for configuring networking,
    since we don't yet have networking and can't apt install them. Then configures
    DNS and network interfaces, then bounces the network interfaces.
    """
    print(" === Setting up networking === ")

    # Install network management packages manually via dpkg, since we can't apt
    # install them without networking already setup.
    print("Installing dependencies for setting up networking...")
    dpkg("-i", *glob("./*.deb"))

    print("Configuring resolved...")
    # Default to the Mikrotik router for DNS, with a fallback of Google's DNS
    sed("-i", "s/^#DNS=$/DNS=172.27.31.254 8.8.8.8/g",
        "/etc/systemd/resolved.conf")
    sed("-i", "s/^#FallbackDNS=$/FallbackDNS=8.8.8.8 8.8.4.4/g",
        "/etc/systemd/resolved.conf")
    systemctl("restart", "systemd-resolved")

    # Not sure if still used, but some things might be expecting orange boxen to
    # have this configuration file.
    with open("/etc/orange-box.conf", "w") as f:
        f.writelines([f"orangebox_number={ob_num}"])

    # Disable the external ethernet port (en*) and use both of the internal
    # ones (enx*). The enx* interfaces map to vlan1 and vlan2, which in turn
    # get mapped to `172.27.{orange box #}.X` and `172.27.{orange box # + 2}.X`,
    # respectively. They are both bridged to the wireless network that the
    # orange box is connected to, hence not needing en* connected.
    print("Writing network configuration...")
    interfaces = list(
        sorted(
            Path(iface).name for iface in glob("/sys/class/net/*")
            if Path(iface).name.startswith("en")))
    internal_ips = [f"172.27.{ob_num}.1", f"172.27.{ob_num + 2}.1"]
    gateway_ips = [f"172.27.{ob_num + 1}.254", f"172.27.{ob_num + 3}.254"]
    sh.ip("addr", "flush", "dev", interfaces[1])
    sh.ifconfig(interfaces[1], f"{internal_ips[1]}/23")
    systemctl("stop", "NetworkManager")
    systemctl("disable", "NetworkManager")

    with open("/etc/network/interfaces", "w") as f:
        f.write(
            textwrap.dedent(f"""
            # These are generated by orange-box build scripts
            auto lo
            iface lo inet loopback

            auto {interfaces[0]}
            iface {interfaces[0]} inet manual

            auto {interfaces[1]}
            iface {interfaces[1]} inet manual

            auto {interfaces[2]}
            iface {interfaces[2]} inet manual

            auto br0
            iface br0 inet static
              address {internal_ips[0]}
              netmask 255.255.254.0
              gateway {gateway_ips[0]}
              dns-nameservers {internal_ips[0]} {gateway_ips[0]}
              bridge_ports {interfaces[1]}
              bridge_stp off
              bridge_fd 0
              bridge_maxwait 0

            auto br1
            iface br1 inet static
              address {internal_ips[1]}
              netmask 255.255.254.0
              bridge_ports {interfaces[2]}
              bridge_stp off
              bridge_fd 0
              bridge_maxwait 0"""))

    print("Restarting network interfaces...")
    bridges = ["br0", "br1"]

    # Take down all of the interfaces
    for iface in interfaces + bridges:
        sh.ifdown("--force", iface)

    # Bring up all interfaces except enp*
    for iface in interfaces[1:] + bridges:
        sh.ifup("--force", iface)

    print("Waiting for network to come up...")
    for _ in range(60):
        try:
            ping("-c1", "8.8.8.8")
            break
        except sh.ErrorReturnCode_1:
            print(" - Still waiting for 8.8.8.8...")
    else:
        print("Waited too long for network to come up.")
        print("Please fix the network.")
        sys.exit(1)

    print("Waiting for DNS to come up...")
    for _ in range(60):
        try:
            ping("-c1", "launchpad.net")
            break
        except (sh.ErrorReturnCode_1, sh.ErrorReturnCode_2):
            print(" - Still waiting for launchpad.net...")
    else:
        print("Waited too long for DNS to come up.")
        print("Please fix the DNS.")
        sys.exit(1)