Error in network definition address is missing prefixlength

Error in network definition address is missing prefixlength Older Versions (Ubuntu 17.10-) With older versions I would just go to /etc/network and edit the interfaces file. This file would have definitions about the computer interfaces, whether each computer gets a static IP or uses DHCP, etc. Here is a sample setup for older versions: […]

Содержание

  1. Error in network definition address is missing prefixlength
  2. Older Versions (Ubuntu 17.10-)
  3. Newer Versions (Ubuntu 18.04+)
  4. Apply Modifications to /etc/netplan/*
  5. What about the WARNING in that yaml file?
  6. What about the Pre-up Script?
  7. Nothing Gets Applied?!
  8. Error: address is missing /prefixlength
  9. Error: gateway unknown field
  10. Where can I find the other fields?
  11. Re: Setting up your static IP address since Ubuntu 18.04
  12. Error in network definition address is missing prefixlength
  13. Answered by:
  14. Question
  15. Answers
  16. All replies
  17. OVH / SoYouStart IP failover / alias – Ubuntu 18.04 + netplan
  18. Introduction
  19. Configuring your new failover IP in Ubuntu 18.04
  20. Before we begin
  21. Configuring netplan
  22. Testing the new netplan configuration

Error in network definition address is missing prefixlength

Older Versions (Ubuntu 17.10-)

With older versions I would just go to /etc/network and edit the interfaces file.

This file would have definitions about the computer interfaces, whether each computer gets a static IP or uses DHCP, etc.

Here is a sample setup for older versions:

The pre-up is a script run before that specific interface gets initialized. In my case, I want to start my firewall (good idea if the interface is for external access: your firewall should be up before the world has a chance to access your computer.)

The DNS name servers is a space separated list of IP addresses used to access the DNS to be used to determine the IP address from a name,

Newer Versions (Ubuntu 18.04+)

The settings themselves have not changed in Ubuntu 18.04, however, the location where it gets setup is completely different. Also the format changed from a plain text Unix like configuration file to a Yaml format declarative setup.

The configuration is also in a new location and uses a file with a completely different name. You will find the file under /etc/plan and it is named 50-cloud-init.yaml .

As we can see, the extension of the file is .yaml. That means it supports any number of sub-options defined by adding more tabs and a different introducer.

First, notice that they mention the netplan replacement and location of the new files. It’s not clear which you have to update to make things work, though.

Now, looking at the /etc/netplan files, by default we see not much is added by default:

Just one file! When you first look at it, you’ll notice that the default is that the computer will automatically be given an IP address through DHCP.

The following is what I use when switching to my local static IP address:

The gateway is generally one of your own computer in an intranet setup.

Two things that make that definition select a static IP address:

1. The dhcp[46]: false;

2. the addresses: . definitions.

My example shows the default route using the routes: . definition because the gateway4: . is being deprecated and will not work anymore at some point soon (deprecated since Ubuntu 21.10).

Apply Modifications to /etc/netplan/*

Whenever you make changes to files under /etc/netplan/. it is required let the netplan know otherwise nothing is going to happen until you reboot.

It should be pretty quick and return to the prompt. After that, you can verify that your changes took hold as expected with:

What about the WARNING in that yaml file?

Yes. You noticed a warning and instructions on how to block the configuration from being blown away. If you’re not going to use the graphical interface, you’re probably safe just like that. On a computer with X-Windows running, I would advice to properly disable the cloud-init as follow:

The file is not likely to already exist. vim will create it as expected just by editing the content of the file.

What about the Pre-up Script?

You may notice that the netplan does not offer any hooks.

The fact is that the netplan is processed using systemd (via the systemd-network service from networkd-dispatcher ), therefore, the solution to implementing a pre-up script is to add your own service file and make sure it runs before the systemd-network service. This will have the same effect.

Here is a sample from the Snap! Websites snapfirewall project:

One of the answers says to write a service file similar to the one used by netfilter-persistent (which depends on iptables-persistent ). On my end, I was wondering on where the files should be installed. So I installed netfilter and looked at the output. Here is the info:

As we can see, the file gets intalled under /lib/systemd/system .

Then a syslink is created as a multi-user.target.wants .

IMPORTANT: The —run-startup-triggers option of the networkd-dispatcher may run after the interface is up. So do not use those events. It’s always going to be too late.

Nothing Gets Applied?!

When you run the command to update your IP addresses, as in:

The netplan may be perfect and all, but when you look at your network with ifconfig , it’s not setup. It uses a default IPv6 address. Note that it will say that it is UP, even though it’s not connected.

When you check out the journal, you will notice a couple of funny messages.

One is by the NetworkManager (which is named that way even by default when you use the networkd renderer):

NetworkManager: definition eno1 is not for us (backend 1)

Another message I’ve seen directly from systemd-networkd is the following:

This is interesting since I just defined that link in the netplan .yaml file and it clearly defines eno1, so. what’s up?

Ha! Ha! Good question, actually the correct question is: what’s down?

And the answer is: your port.

This will change in the future (according to the messages I’ve seen), but if you disconnect your network cable, your computer does not see a carrier and it decides not to setup the port. At least not until it sees a carrier again. From what they are saying, the detection of the carrier will trigger an event and setup the netplan at that time. I’ve not tried that to see if it is true. I may do so later.

So. as a result, to setup your port, you need to have a valid network card connected to your router or your switch or your hub (are network hubs still being sold? switches are so cheap now, I don’t see why we’d still need hubs.)

To see more info about your network session, you can use the journalctl command like so:

The -e option is to bring you at the end of that journal. You may have to go up a bit to see the entire session startup sequence.

Error: address is missing /prefixlength

The static IP address you are assigning to the computer must include a mask. This is the «/ » at the end of the address. In my example above, I used «/8» giving me a giant network (up to 16 million computers in my LAN.)

Here is another example with a 192.168.x.x where we limit the number of computers to about 250. Netplan gives you the error above when that prefix length was not specified.

Note: For old timers (like me), it is important to understand that newer network settings do not support masks anymore (are not expected to support such). Instead, they have a prefix length. In other words, the mask is all zeroes except for the number of bits specified by the prefix length.

Error: gateway unknown field

I got that one error once too. Note that the gateway specification in the old interfaces file used the word gateway to specify that IP address.

Netplan, on the other hand, uses gateway4 and gateway6 so it can be sure it’s parsing the correct type of IP address.

The documentation doesn’t say and I haven’t tried, but it is likely that both will work together. I would only use one or the other. Test which works best for you and stick to it.

Where can I find the other fields?

You should already know that since it shows up in the old interfaces file.

For additional information, use the manual with the following:

For example you could specify the size of the MTU (not really recommanded, although on a local network, having a larger MTU could help with large transfers.) There are also options to setup routes. Usually the default is enough, but on a rather specific network, adding a few routes could be useful and it can be done at this point.

Re: Setting up your static IP address since Ubuntu 18.04

You, sir, are amazing, was having so much trouble with the error: address is missing /prefix-length

Your explanation sorted it for me, unlike several others I was trying to sort it.

Источник

Error in network definition address is missing prefixlength

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

Great but now I don’t have a gateway or DNS or a valid subnet.

did not have luck with net use in cli either.

Btw, why no .conf file? I mean, we don’t have .conf files in Windows, I guess?

Answers

Not sure what your exact question is, but on your first entry, you have a — in front of the IP address which is why the cmdlet is failing

— ipaddress — 10.245 . 245.23 should be — ipaddress 1 0.245 . 245.23

If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.

Not sure what your exact question is, but on your first entry, you have a — in front of the IP address which is why the cmdlet is failing

— ipaddress — 10.245 . 245.23 should be — ipaddress 1 0.245 . 245.23

If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.

I have tried many variations.

Exact question: «Setup Static IP Address Server Core 2012 R2 using powershell»

I have looked at several technets and third party blogs:

etc. or just a text file seems simpler. But, that’s probably just because that is what I am used to in heathen operating systems.

Is this the correct syntax, but I have to remove the previous entry first?

You are still adding a dash in front of the address and the gateway.

You must remove those.

So I just need a gateway and mask:

IPAddress : 10.245.245.23
InterfaceIndex : 12
InterfaceAlias : Ethernet
AddressFamily : IPv4
Type : Unicast
PrefixLength : 32
PrefixOrigin : Manual
SuffixOrigin : Manual
AddressState : Preferred
ValidLifetime : Infinite ([Tim
PreferredLifetime : Infinite ([Tim
SkipAsSource : False
PolicyStore : ActiveStore

PS C:UsersAdministrator> ipconfig

Windows IP Configuration

Ethernet adapter Ethernet:

Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::ec97:2025:b0fd:5bea%12
IPv4 Address. . . . . . . . . . . : 10.245.245.23
Subnet Mask . . . . . . . . . . . : 255.255.255.255
Default Gateway . . . . . . . . . :

Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :

Now you’ve removed too many dashes. You must still keep the dash before the parameters.

No, i have tried that variation and several others listed on TechNet and blogs / forums.

This should be really, really easy.

PS C:UsersAdministrator> new-netipaddress -interfaceindex 12 -ipaddress 10.245.245.23 -prefixlength
27 -defaultgateway 10.245.245.1
new-netipaddress : Instance MSFT_NetIPAddress already exists
At line:1 char:1
+ new-netipaddress -interfaceindex 12 -ipaddress 10.245.245.23 -prefixlength 27 -d .
+

+ CategoryInfo : InvalidArgument: (MSFT_NetIPAddress:ROOT/StandardCimv2/MSFT_NetIPAddr
ess) [New-NetIPAddress], CimException
+ FullyQualifiedErrorId : Windows System Error 87,New-NetIPAddress

Источник

OVH / SoYouStart IP failover / alias – Ubuntu 18.04 + netplan

Introduction

OVH and SoYouStart offer free failover IP’s with dedicated servers. You initially request a new failover IP address directly with OVH / SoYouStart – just login to your control panel and request a new failover IP. Once you have received your new IP(s) you have to manually assign them to your server (it’s not automatic).

Below is a screenshot of the SoYouStart IP request:

Once you have been supplied the requested IP failover / IP alias, it will appear under allocated to your chosen server.

Let us assume we requested 2 ips and were given the following:

  • Failover 1: 123.45.67.8
  • Failover 2: 123.45.67.99

Configuring your new failover IP in Ubuntu 18.04

Now that we have our IP, it won’t automatically be configured on the actual Ubuntu 18.04 server. You have to do this manually.

Unfortunately Ubuntu 18.04 no longer includes ifupdown as default. Instead netplan is bundled for network interfacing. You can install ifupdown and use that but you may as well get used to netplan moving forward.

If you want to go back to ifupdown, read details here: https://netplan.io/faq#how-to-go-back-to-ifupdown

Before we begin

First all of we need to take note of your current servers ethernet card details (assuming you only have one ethernet card). We need the following details:

  • Network interface name
  • MAC address

Type in the following command to get these details:

Hopefully you get an output similar to the following:

I have highlighted in green and yellow the network interface name and mac address for my server. We are going to use this information to help configure the new IP failover using netplan.

  • Network interface name: eno1
  • MAC address: x8:50:f6:2x:67:8x

Configuring netplan

The first thing is to create a new custom netplan configuration file. Head over to your /etc/netplan folder and create a new empty configuration file (call it anything but it must end with a .yaml extension).

I’m going to call my file config.yaml. I am going to use nano editor but feel free to use whatever you are comfortable with.

If we go back and list all the information we have gathered, we are going to use this information in our new config.yaml file to bind the 2 new failover IP’s to our server:

  • Network interface name: eno1
  • MAC address: x8:50:f6:2x:67:8x
  • Failover 1: 123.45.67.8
  • Failover 2: 123.45.67.99

Paste and edit the following in to your empty config.yaml:

Note: It is very important that the indentation is correct since this is a YAML file and YAML syntax has fixed indentation rules (more on that here: https://docs.saltstack.com/en/latest/topics/yaml/).

If you do not have the correct indentation, it is likely netplan will throw an error when you try to test / restart it.

As you can see we have populated the details such as the Network Interface Name (eno1),MAC address (x8:50:f6:2x:67:8x) and added each of our failover IP’s after the line addresses:

We have then also added a subnet mask of /32 to each of the IP’s.

Save the file and exit the editor.

Testing the new netplan configuration

Now that we have successfully saved our file, we want to test it to see if it works, run the following command netplan try:

You should see a successful output like the following:

Excellent – now that we have verified the configuration looks good, lets apply the changes: Run the command netplan apply.

Now all we need to do is verify that the new failover IPs have been assigned to the server, run the command ip addr list:

As you can see, our new failover IP’s have been assigned to the server.

Источник

~# sudo netplan apply
/etc/netplan/01-netcfg.yaml:16:18: Error in network definition: address '8.8.8.8' is missing /prefixlength
      addresses: [8.8.8.8,8.8.4.4]
                 ^

Eliah Kagan's user avatar

Eliah Kagan

115k53 gold badges311 silver badges484 bronze badges

asked Nov 28, 2019 at 11:49

Feku Real Estate Agents's user avatar

network:
 version: 2
 ethernets: {}
 renderer: networkd
 ethernets:
  ens160:
  dhcp4: no
  addresses: [206.80.236.251/29]
  gateway4: 206.80.236.249
  nameservers: 
    addresses: [8.8.8.8,8.8.4.4]

Make sure you are spacing correctly at exactly this stage :

nameserver 

should be aligned with gateway & addresses while spacing

damadam's user avatar

damadam

2,7653 gold badges16 silver badges37 bronze badges

answered Nov 28, 2019 at 11:58

VIX's user avatar

Spider Web representing various Internet and Intranet network of users.

Older Versions (Ubuntu 17.10-)

With older versions I would just go to /etc/network and edit the interfaces file.

This file would have definitions about the computer interfaces, whether each computer gets a static IP or uses DHCP, etc.

Here is a sample setup for older versions:

auto eth0
iface eth0 inet static
        address 10.0.0.1
        netmask 255.0.0.0
        network 10.0.0.0
        broadcast 10.255.255.255
        gateway 10.0.0.1
        dns-nameservers 10.0.0.8 10.0.0.9
        dns-search m2osw.com
        pre-up /etc/network/firewall

The pre-up is a script run before that specific interface gets initialized. In my case, I want to start my firewall (good idea if the interface is for external access: your firewall should be up before the world has a chance to access your computer.)

The DNS name servers is a space separated list of IP addresses used to access the DNS to be used to determine the IP address from a name,

Newer Versions (Ubuntu 18.04+)

The settings themselves have not changed in Ubuntu 18.04, however, the location where it gets setup is completely different. Also the format changed from a plain text Unix like configuration file to a Yaml format declarative setup.

The configuration is also in a new location and uses a file with a completely different name. You will find the file under /etc/plan and it is named 50-cloud-init.yaml.

As we can see, the extension of the file is .yaml. That means it supports any number of sub-options defined by adding more tabs and a different introducer.

First, notice that they mention the netplan replacement and location of the new files. It’s not clear which you have to update to make things work, though.

$ cat /etc/network/interfaces
# ifupdown has been replaced by netplan(5) on this system.  See
# /etc/netplan for current configuration.
# To re-enable ifupdown on this system, you can run:
#    sudo apt install ifupdown

Now, looking at the /etc/netplan files, by default we see not much is added by default:

$ find /etc/netplan/ -exec ls -ld {} ;
drwxr-xr-x 2 root root 4096 Apr  5 21:03 /etc/netplan/
-rw-r--r-- 1 root root  589 Apr  5 21:03 /etc/netplan/50-cloud-init.yaml

Just one file! When you first look at it, you’ll notice that the default is that the computer will automatically be given an IP address through DHCP.

The following is what I use when switching to my local static IP address:

# This file is generated from information provided by
# the datasource.  Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
    ethernets:
        enp0s3:
            addresses: [10.0.0.15/8]
            dhcp4: false
            dhcp6: false
            optional: false
            #gateway4: 10.0.0.1
            nameservers:
                addresses: [75.75.75.75,75.75.76.76]
            routes:
                - to: 0.0.0.0/0
                  via: 10.0.0.1
                  metric: 100
    version: 2

The gateway is generally one of your own computer in an intranet setup.

Two things that make that definition select a static IP address:

1. The dhcp[46]: false;

2. the addresses: … definitions.

My example shows the default route using the routes: … definition because the gateway4: … is being deprecated and will not work anymore at some point soon (deprecated since Ubuntu 21.10).

Apply Modifications to /etc/netplan/*

Whenever you make changes to files under /etc/netplan/… it is required let the netplan know otherwise nothing is going to happen until you reboot.

sudo netplan apply

It should be pretty quick and return to the prompt. After that, you can verify that your changes took hold as expected with:

ifconfig

What about the WARNING in that yaml file?

Yes. You noticed a warning and instructions on how to block the configuration from being blown away. If you’re not going to use the graphical interface, you’re probably safe just like that. On a computer with X-Windows running, I would advice to properly disable the cloud-init as follow:

# Open file
$ sudo vim /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg

# Add this line (i for insert and then type the following)
network: {config: disabled}

# Then save and exit (:wq or ZZ)

The file is not likely to already exist. vim will create it as expected just by editing the content of the file.

What about the Pre-up Script?

You may notice that the netplan does not offer any hooks.

The fact is that the netplan is processed using systemd (via the systemd-network service from networkd-dispatcher), therefore, the solution to implementing a pre-up script is to add your own service file and make sure it runs before the systemd-network service. This will have the same effect.

Here is a sample from the Snap! Websites snapfirewall project:

# Documentation available at:
# https://www.freedesktop.org/software/systemd/man/systemd.service.html

# This service is used on 18.04 and newer systesm where the ifup/ifdown
# interfaces file is not used anymore; it replaces our `pre-up ...` call

[Unit]
Description=Snap! Websites snapfirewall initialization on boot
Wants=network-pre.target
Before=network-pre.target

[Service]
Type=oneshot
WorkingDirectory=~
ProtectHome=true
NoNewPrivileges=false
# We will change this path once we have a better script to setup the firewall
ExecStart=/etc/network/firewall
Restart=no

[Install]
WantedBy=network.target

# vim: syntax=dosini

One of the answers says to write a service file similar to the one used by netfilter-persistent (which depends on iptables-persistent). On my end, I was wondering on where the files should be installed. So I installed netfilter and looked at the output. Here is the info:

Created symlink:
   /etc/systemd/system/multi-user.target.wants/netfilter-persistent.service →
   /lib/systemd/system/netfilter-persistent.service.

As we can see, the file gets intalled under /lib/systemd/system.

Then a syslink is created as a multi-user.target.wants.

Source: How to start a systemd service before networking starts?

IMPORTANT: The —run-startup-triggers option of the networkd-dispatcher may run after the interface is up. So do not use those events. It’s always going to be too late.

Nothing Gets Applied?!

When you run the command to update your IP addresses, as in:

sudo netplan apply

The netplan may be perfect and all, but when you look at your network with ifconfig, it’s not setup. It uses a default IPv6 address. Note that it will say that it is UP, even though it’s not connected.

When you check out the journal, you will notice a couple of funny messages.

One is by the NetworkManager (which is named that way even by default when you use the networkd renderer):

NetworkManager: definition eno1 is not for us (backend 1)

Another message I’ve seen directly from systemd-networkd is the following:

eno1: Link is not managed by us

This is interesting since I just defined that link in the netplan .yaml file and it clearly defines eno1, so… what’s up?

Ha! Ha! Good question, actually the correct question is: what’s down?

And the answer is: your port.

This will change in the future (according to the messages I’ve seen), but if you disconnect your network cable, your computer does not see a carrier and it decides not to setup the port. At least not until it sees a carrier again. From what they are saying, the detection of the carrier will trigger an event and setup the netplan at that time. I’ve not tried that to see if it is true. I may do so later.

So… as a result, to setup your port, you need to have a valid network card connected to your router or your switch or your hub (are network hubs still being sold? switches are so cheap now, I don’t see why we’d still need hubs.)

To see more info about your network session, you can use the journalctl command like so:

journalctl -xeu ststemd-networkd

The -e option is to bring you at the end of that journal. You may have to go up a bit to see the entire session startup sequence.

See Also: Why is Netplan/Networkd not bringing up a static ethernet interface?

Error: address is missing /prefixlength

The static IP address you are assigning to the computer must include a mask. This is the «/<number>» at the end of the address. In my example above, I used «/8» giving me a giant network (up to 16 million computers in my LAN.)

            addresses: [192.168.55.35/24]

Here is another example with a 192.168.x.x where we limit the number of computers to about 250. Netplan gives you the error above when that prefix length was not specified.

Note: For old timers (like me), it is important to understand that newer network settings do not support masks anymore (are not expected to support such). Instead, they have a prefix length. In other words, the mask is all zeroes except for the number of bits specified by the prefix length.

Error: gateway unknown field

I got that one error once too. Note that the gateway specification in the old interfaces file used the word gateway to specify that IP address.

Netplan, on the other hand, uses gateway4 and gateway6 so it can be sure it’s parsing the correct type of IP address.

The documentation doesn’t say and I haven’t tried, but it is likely that both will work together. I would only use one or the other. Test which works best for you and stick to it.

Where can I find the other fields?

You should already know that since it shows up in the old interfaces file…

For additional information, use the manual with the following:

man 5 netplan

For example you could specify the size of the MTU (not really recommanded, although on a local network, having a larger MTU could help with large transfers.) There are also options to setup routes. Usually the default is enough, but on a rather specific network, adding a few routes could be useful and it can be done at this point.

  • Печать

Страницы: [1]   Вниз

Тема: Поднимите мне брови! netplan … не получается добавить bond интерфейс  (Прочитано 1209 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
Elias292

Конфиг такой:

root@ubuntu:/etc/netplan# cat 00-installer-config.yaml

Пытаюсь применить:

root@ubuntu:/etc/netplan# netplan try --state /etc/netplan
/etc/netplan/00-installer-config.yaml:28:9: Error in network definition: unknown key 'bond0'
        bond0:
        ^

An error occurred: the configuration could not be generated


Вот что за фигня ?

Что-то типа такого должно быть.

« Последнее редактирование: 02 Мая 2022, 16:09:37 от Morisson »


Оффлайн
Morisson

Оформите свое сообщение согласно правил форума. В противном случае оно будет удалено.
Спасибо за понимание.


Оффлайн
Elias292

Оформите свое сообщение согласно правил форума. В противном случае оно будет удалено.
Спасибо за понимание.

Что не так в моем сообщении ?


Оффлайн
Morisson

1.4. Листинги и содержимое текстовых файлов следует добавлять в сообщение с помощью тегов

или

..., либо прикреплять к сообщению в виде отдельного файла. Длинные гиперссылки следует оформлять при помощи тега ….

https://forum.ubuntu.ru/index.php?action=rules


Онлайн
ALiEN175

Вот что за фигня ?

Пробелы в начале строк правильно посчитаны? Для YAML это очень важно.

ASUS P5K-C :: Intel Xeon E5450 @ 3.00GHz :: 8 GB DDR2 :: Radeon R7 260X :: XFCE
ACER 5750G :: Intel Core i5-2450M @ 2.50GHz :: 6 GB DDR3 :: GeForce GT 630M :: XFCE


Оффлайн
Elias292

В общем…

Конфиг щас такой

Когда даю комманду:

root@ubuntu:/etc# netplan try --state /etc/netplan

bond0: reverting custom parameters for bridges and bonds is not supported

Please carefully review the configuration and use 'netplan apply' directly.


Командой netplan apply
все применяется…
Но сервисы почему то вешаются на ipv6

root@ubuntu:/var/log/munin# !netst
netstat -nlp | grep 4949
tcp6       0      0 :::4949                 :::*                    LISTEN      355919/perl

netplan — отстой!


Пользователь добавил сообщение 02 Мая 2022, 17:43:56:


Вот что за фигня ?

Пробелы в начале строк правильно посчитаны? Для YAML это очень важно.

Где б еще узнать как оно «правильно».

« Последнее редактирование: 02 Мая 2022, 17:43:56 от Elias292 »


Оффлайн
bezbo


Оффлайн
Elias292

Поднимите мне брови!

netplan

Ничего полезного я тут не нашел.
Это заклинания какие-то, без объяснения что и зачем тут написано.


  • Печать

Страницы: [1]   Вверх

Ser8191

0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

1

11.11.2021, 15:18. Показов 6300. Ответов 29

Метки нет (Все метки)


Здравствуйте.
Установил Ubuntu Server 20.04.3
Нужно назначить статический IP адрес 192.168.1.35
В каталоге /etc/netplan три файла:

00-installer-config-wifi.yaml
01-installer-config.yaml
01-netcfg.yaml

Команда

PowerShell
1
ip a

выдаёт следующее:

Код

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp3s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 28:d2:44:b0:b4:fe brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.39/24 brd 192.168.1.255 scope global dynamic enp3s0
       valid_lft 24006sec preferred_lft 24006sec
    inet6 fe80::2ad2:44ff:feb0:b4fe/64 scope link
       valid_lft forever preferred_lft forever
3: wlp2s0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 18:cf:5e:e7:34:c9 brd ff:ff:ff:ff:ff:ff

Меняю содержимое файла 01-installer-config.yaml

Код

network:
version: 2
renderer: networkd
ethernets:
enp0s3:
dhcp4: no
addresses: [192.168.1.35/24]
gateway4: 192.168.1.1
nameservers:
addresses: [8.8.8.8, 8.8.4.4]

Выполняю команду:

PowerShell
1
sudo netplan apply

Получаю ошибку:

PowerShell
1
2
/etc/netplan/01-installer-config.yaml:1:9: Error in network definition: expected mapping (check indentation)
network:

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



4732 / 3937 / 997

Регистрация: 29.08.2013

Сообщений: 25,248

Записей в блоге: 3

11.11.2021, 16:42

2

а точно нужно прописывать 192.168.1.35/24?
может быть отдельно IP и отдельно маску?



0



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 16:46

 [ТС]

3

Без понятия. Что нашёл, то м попробовал.
Уровень знаний минимальный.



0



4732 / 3937 / 997

Регистрация: 29.08.2013

Сообщений: 25,248

Записей в блоге: 3

11.11.2021, 16:47

4

проверяй по разному
попробуй и без /24 и без []



1



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 18:36

 [ТС]

5

Как я понял дело в табуляции, нужно соблюдать пробелы

Код

/etc/netplan/00-installer-config.yaml:4:1: Invalid YAML: tabs are not allowed for indent:
        enp3s0:

Добавлено через 9 минут

Код

sudo nano /etc/netplan/00-installer-config.yaml

network:
  version: 2
  ethernets:
    enp0s3:
      dhcp4: no
      dhcp6: no
      addresses: [10.0.2.15/24]
      gateway4: 10.0.2.1
      nameservers:
        addresses: [8.8.8.8, 8.8.4.4]


sudo netplan apply

После данных манипуляций связь по ssh пропадает.
На сервере следующая информация

Миниатюры

Статический IP Ubuntu Server 20.04.3
 



0



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 19:08

 [ТС]

6

Валидатор YAML пишет что файл валидный, даже если использую табуляцию



0



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 19:38

 [ТС]

7

С ошибкой разобрался, использовал пробелы.
Но адрес не меняется.

Миниатюры

Статический IP Ubuntu Server 20.04.3
 



0



Эксперт NIX

2658 / 777 / 173

Регистрация: 14.01.2013

Сообщений: 3,585

11.11.2021, 19:43

8

Вот вариант с рабочего сервера

Код

network:
  version: 2
  renderer: networkd
  ethernets:
    enp2s0:
      dhcp4: no
      dhcp6: no
      addresses: [ 172.16.0.88/24 ]
      gateway4: 172.16.0.81
      nameservers:
        addresses: [ 172.16.0.81, 77.88.8.1 ]



0



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 19:46

 [ТС]

9

Да в принципе у меня тоже самое, но ip a показывает туже информацию из верхнего скрина, и нет связи по указанному адресу



0



_sg2

594 / 204 / 40

Регистрация: 30.08.2017

Сообщений: 1,339

11.11.2021, 20:03

10

renderer: networkd
а может и NetworkManager. У Вас там что?
Вообще проверьте все пробелы. рекомендую ВЕЗДЕ отступы в 2 пробела. Ну или по стандарту python 4. Но ВЕЗДЕ одинаково, будет лишний где/не хватать, парсер YAML может заругаться. Я пару раз мимоходом этот netplan курил, сложностей не вызывало кроме необходимости очередную ересь изучить и попробовать запомнить (не удалось ).
Проверить что накалякали (если память не подводит):

Bash
1
netplan --debug generate

Почитать ошибки, устранить и

Bash
1
netplan apply

Кажеться так. Ну и у уважаемого Kubuntovod, рабочий вариант как шпаргалка.



0



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 20:09

 [ТС]

11

Миниатюры

Статический IP Ubuntu Server 20.04.3
 



0



594 / 204 / 40

Регистрация: 30.08.2017

Сообщений: 1,339

11.11.2021, 20:10

12

доступ запрещён написано
значит sudo
и неужели нельзя скопировать с терминала, зачем мутные фото?



0



Эксперт по компьютерным сетямЭксперт NIX

12384 / 7223 / 758

Регистрация: 09.09.2009

Сообщений: 28,185

11.11.2021, 20:11

13

в роутере назначить айпишник «серверу» — не?



0



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 20:16

 [ТС]

14

и неужели нельзя скопировать с терминала, зачем мутные фото?

Скопировать можно было бы, если бы работал по ssh, но ip адрес то не выставляется, и рабочий ПК не видит сервер.

в роутере назначить айпишник «серверу» — не?

Связь будет без роутера, в этом и проблема (с роутером всё работало)

доступ запрещён написано
значит sudo

Про sudo забыл…

Миниатюры

Статический IP Ubuntu Server 20.04.3
 



0



594 / 204 / 40

Регистрация: 30.08.2017

Сообщений: 1,339

11.11.2021, 20:22

15

А. Это отдельная физическая машина…
А чё там такое намешано? OpenVSwitch, NetworkManager. Ужасы какие-то, вот не помню
Ну кажись не инвалид конфиг.. и что netplan apply выдал?



0



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 20:25

 [ТС]

16

А чё там такое намешано? OpenVSwitch, NetworkManager. Ужасы какие-то, вот не помню

Ubuntu Server 20.04.3 (64-bit)

и что netplan apply выдал?

Ответа нет, переход к вводу новой команды.



0



594 / 204 / 40

Регистрация: 30.08.2017

Сообщений: 1,339

11.11.2021, 20:28

17

Ну и ip a?
systemctl status networkd?
Мы тут мысли читать не умеем, уж извините



0



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 20:34

 [ТС]

18

Попробовал на других соединениях и вернулся к своему, адрес поменялся, но не пингуется.

Миниатюры

Статический IP Ubuntu Server 20.04.3
 



0



0 / 0 / 0

Регистрация: 17.01.2017

Сообщений: 179

11.11.2021, 20:49

 [ТС]

19

Перезагрузил сервер полностью обесточив.
Выполнил те-же действия, IP стал виден.
Перезагрузил.
Такая же ерунда.
Выполнил netplan apply, заработало.
Переустанавливаю сервер. Отпишусь.



0



594 / 204 / 40

Регистрация: 30.08.2017

Сообщений: 1,339

11.11.2021, 20:59

20

меня смущает какой-то ip на loopback



0



I am stuck:

PS C:UsersAdministrator> new-netipaddress -interfaceindex 12 -ipaddress -10.245.245.23 -prefixlengt h 27 -defaultgateway -10.245.245.1 new-netipaddress : Invalid parameter IPv4Address -10.245.245.23 At line:1 char:1 + new-netipaddress -interfaceindex 12 -ipaddress -10.245.245.23 -prefixlength 27 - ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (MSFT_NetIPAddress:ROOT/StandardCimv2/MSFT_NetIPAddr ess) [New-NetIPAddress], CimException + FullyQualifiedErrorId : Windows System Error 87,New-NetIPAddress

C:UsersAdministrator>ipconfig

Windows IP Configuration
Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::ec97:2025:b0fd:5bea%12
   Autoconfiguration IPv4 Address. . : 169.254.91.234
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . :

Tunnel adapter isatap.{BD4269C9-C153-45D6-9C5C-633658434B83}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
PS C:UsersAdministrator> new-netipaddress

cmdlet New-NetIPAddress at command pipeline position 1
Supply values for the following parameters:
IPAddress: 10.245.245.23
InterfaceAlias: Ethernet

IPAddress         : 10.245.245.23
InterfaceIndex    : 12
InterfaceAlias    : Ethernet
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 32
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Tentative
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore

IPAddress         : 10.245.245.23
InterfaceIndex    : 12
InterfaceAlias    : Ethernet
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 32
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Invalid
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : PersistentStore

Great but now I don’t have a gateway or DNS or a valid subnet.

did not have luck with net use in cli either.

Btw, why no .conf file? I mean, we don’t have .conf files in Windows, I guess?


Прочитано:
24 571

Как я понял, теперь в Ubuntu 18.04 за основную утилиту для настройки сетевых настроек из командной строки — это netplan. Настройка работы интерфейсов сводится к правильному конфигурированию через абстракцию YAML.

На заметку: При настройке конфигурационного файла netplan самое глачное не использовать символы табуляции, только символы пробела. Именно это и есть абстракция использования YAML (Yet Another Markup Language» — «Ещё один язык разметки»)

ekzorchik@srv-bionic:~$ sudo apt remove ifupdown -y

Отобразить все сетевые интерфейсы системы:

ekzorchik@srv-bionic:~$ ifconfig -a

  • интерфейс в выводе: epn0s3 → это сетевой интерфейс на который настроена система
  • интерфейс в выводе: lo → интерфейс обратной петли (loopback)

Если система установлена, а интерфейс не назначен системой или системе, то при просмотре конфигурационного файла утилиты netplan содержимое ничего не содержит, нужно его сформировать:

ekzorchik@srv-bionic:~$ sudo netplan generate

Чтобы установить статический IP-адрес:

ekzorchik@srv-bionic:~$ sudo nano /etc/netplan/01-netcfg.yaml

network:

version: 2

renderer: networkd

ethernets:

# имя сетевого интерфейса

enp0s3:

# активация или дезактивация получения настроек от DHCP-сервиса для IPv4

# можно указывать, как no/yes так и true/false

dhcp4: no

# активация или дезактивация получения настроек от DHCP-сервиса для IPv6

# можно указывать, как no/yes так и true/false

dhcp6: no

# установка статического адреса с указанием действующей маски подсети

addresses: 172.40.40.25/24

# установка шлюза для IPv4 (по умолчанию)

gateway4: 172.40.40.1

# установка DNS-серверов, если в доменной сети, то указываем IP адреса контроллеров домена, если без домена, то адрес Вашего маршрутизатора или же публичные DNS: 8.8.8.8, 8.8.4.4 или DNS провайдера.

nameservers:

addresses: [172.40.40.1,172.40.40.8]

Не забываем сохранить внесенные изменения и применить:

ekzorchik@srv-bionic:~$ sudo netplan apply

Error in network definition //etc/netplan/01-netcfg.yaml line 7 column 14: expected sequence

Если в файле конфигурации присутствует ошибка она будет выведена на консоль и ее нужно исправить т.к. изменения не будут применены. Подсказка: седьмая строка и четырнадцатый символ в моем случае.

Addresses: [172.40.40.25/24] → нужны квадратные скобки

Итоговый конфигурационный файл:

network:

version: 2

# Выбор сетевого рендера. Выбран networkd

renderer: networkd

# Блок с настройкой сетевых интерфейсов

ethernets:

enp0s3:

dhcp4: no

dhcp6: no

addresses: [172.40.40.25/24]

macaddress: 08.00.27.28.31.1f

gateway4: 172.40.40.1

nameservers:

addresses: [172.40.40.1]

Чтобы установить динамический IP-адрес:

ekzorchik@srv-bionic:~$ sudo nano /etc/netplan/01-netcfg.yaml

network:

version: 2

renderer: networkd

ethernets:

enp0s3:

dhcp4: yes

dhcp6: no

ekzorchik@srv-bionic:~$ sudo netplan apply

На заметку: как всегда расширенную информацию по использованию следует черпать в справочном файле: ekzorchik@srv-bionic:~$ man netplan

Чтобы установить несколько сетевых интерфейсов, то их можно либо разбить, как каждый конфигурационный файл с расширением yaml или все указать в едином. Просто начав с новой строки именованием второго или более сетевым интерфейсом:

ekzorchik@srv-bionic:~$ sudo nano /etc/netplan/01-netcfg.yaml

network:

version: 2

renderer: networkd

ethernets:

enp0s3:

dhcp4: yes

dhcp6: false

enp0s4:

dhcp4: no

addresses: [172.40.40.26/24]

gateway4: 172.40.40.1

nameservers:

addresses: [8.8.8.8]

dhcp6: no

ekzorchik@srv-bionic:~$ sudo netplan apply

Чтобы проверить правильность конфигурационного файла на ошибки:

ekzorchik@srv-bionic:~$ sudo netplan try

Warning: Stopping systemd-networkd.service, but it can still be activated by:

systemd-networkd.socket

Do you want to keep these settings?

Press ENTER before the timeout to accept the new configuration

Changes will revert in 118 seconds

Configuration accepted.

И если все правильно сказать системе нажатием клавиши Enter применить их.

А после проверяем, что интерфейс поднялся и получил или был назначен:

ekzorchik@srv-bionic:~$ sudo ifconfig -a

Установить сетевой интерфейс использую NetworkManager если настройка ведется через интерфейс wifi:

ekzorchik@navy:~$ sudo nano /etc/netplan/01-network-manager-all.yaml

network:

version: 2

renderer: NetworkManager

wifis:

wlp3s0:

dhcp4: no

addresses: [172.40.40.7/24]

gateway4: 172.40.40.1

nameservers:

addresses: [172.40.40.1,8.8.8.8]

access-points:

ekzorchik:

password: "Aa1234567"

ekzorchik@navy:~$ sudo netplan apply

ekzorchik@navy:~$ sudo ifconfig -a | egrep -E "wlp3s0|inet"

inet 127.0.0.1 netmask 255.0.0.0

inet6 ::1 prefixlen 128 scopeid 0x10<host>

wlp3s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500

inet 172.40.40.7 netmask 255.255.255.0 broadcast 172.40.40.255

inet6 fe80::96d1:8a4e:ed15:9be8 prefixlen 64 scopeid 0x20<link>

И если все правильно указано для подключения к точке доступа, то интерфейс поднимется и подключиться к Wi-Fi и в зависимости от настроек получит сетевой адрес, как у меня. Для справки Wi-Fi подключение работает на базе Mikrotik. Скорее всего у Вас также как у меня при подключении к Wi-Fi сетевой адрес выдает от DHCP-сервиса и тогда конфигурационный файл можно сократить до вида:

network:

version: 2

renderer: NetworkManager

wifis:

wlp3s0:

dhcp4: yes

access-points:

ekzorchik:

password: "Aa1234567"

Дабы не мудрить с правильность настройки конфигурационного файла под интерфейса за основу можно взять один из примеров прилагаемых вместе с утилитой netplan:

ekzorchik@navy:~$ ls /usr/share/doc/netplan.io/examples/

bonding_router.yaml direct_connect_gateway.yaml static.yaml

bonding.yaml loopback_interface.yaml vlan.yaml

bridge_vlan.yaml network_manager.yaml windows_dhcp_server.yaml

bridge.yaml source_routing.yaml wireless.yaml

dhcp.yaml static_multiaddress.yaml

ekzorchik@navy:~$ sudo cp /usr/share/doc/netplan.io/examples/wireless.yaml /etc/netplan/01-networkd.yaml

На заметку: любой настроечный файл в каталоге /etc/netplan будет обрабатываться утилитой netplan имеющий расширение yaml.

Вот мой рабочий конфиг с ноутбука Lenovo E555 системы Ubuntu 18.04 Desktop amd64, если нажать клавишу F8 то выключаем Wi-Fi, если подключен кабель ethernet, то настройки автоматически присваиваются и интернет и локальная сеть есть, если вытаскиваю кабель, а включаю Wi-Fi то также интернет есть, если оба интерфейса включены то интернет также есть:

ekzorchik@navy:~$ sudo nano /etc/netplan/01-networkd.yaml

network:

version: 2

renderer: NetworkManager

ethernets:

enp0s3:

dhcp4: yes

wifis:

wlp3s0:

dhcp4: yes

access-points:

ekzorchik:

password: "Aa1234567"

ekzorchik@navy:/etc/netplan$ sudo netplan apply

На заметку: в файле ekzorchik@navy:~$ cat /etc/network/interfaces все закомментировано, за исключением:

auto lo

iface lo inet loopback

Итого, я для себя разобрал, как настраивается сетевой интерфейс(ы) через утилиту netplan в системе Ubuntu 18.04 независимо от используемой редакции, как Server или Desktop. На этом я прощаюсь, с уважением автор блога Олло Александр aka ekzorchik.


I need to set the IP address of a NIC on Windows 10 while it is not connected to a network. I’ve tried:

Set-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress "192.168.5.10" -PrefixLength 24

and

New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress "192.168.5.10" -PrefixLength 24

Set-NetIPAddress does not return any errors, but it doesn’t set the address. It does toggle the selection in IPV4 properties to use a specific address, but does not fill in the values.

New-NetIPAddress gives the following error:

New-NetIPAddress : Inconsistent parameters PolicyStore PersistentStore and     Dhcp Enabled
At line:1 char:1
+ New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress "192.168.5.10" -Pr     ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (MSFT_NetIPAddress:ROOT/StandardCimv2/MSFT_NetIPAddress) [New-NetIPAddress], CimException
+ FullyQualifiedErrorId : Windows System Error 87,New-NetIPAddress

I did some digging and found here: http://www.darrylvanderpeijl.nl/tag/policystore/ that the NIC needs a connection before configuring the IP address.

Basically I am trying to set the IP address for add-on NICS in hundreds of computers. This particular NIC will not have a connection until the computer is in production. I’m still pretty new to Powershell, is it even possible to configure the IP address of a disconnected NIC?

I’m open to trying other technologies if needed.

Понравилась статья? Поделить с друзьями:
  • Error in maximum call stack size exceeded angular
  • Error in maximize unexpected options
  • Error in materialized view or zonemap refresh path
  • Error in mapinfo file access library
  • Error in main wine