Linux изменить сетевое имя

Как установить или изменить имя хоста в Linux

По умолчанию системное имя хоста задается во время процесса установки или, если вы создаете виртуальную машину, оно динамически назначается экземпляру при запуске, но бывают ситуации, когда вам нужно изменить его.

Это руководство проведет вас через процесс изменения имени хоста в Linux без перезапуска системы. Инструкции должны работать с любым современным дистрибутивом Linux, использующим systemd.

Что такое имя хоста

Имя хоста — это метка, присвоенная машине, которая идентифицирует машину в сети. Каждое устройство в сети должно иметь уникальное имя хоста.

Имя хоста может быть простой строкой, содержащей буквенно-цифровые символы, точки и дефисы. Если машина подключена к Интернету (например, к веб-серверу или почтовому серверу), рекомендуется использовать полное доменное имя (FQDN) в качестве имени хоста системы. Полное доменное имя состоит из двух частей: имени хоста и имени домена.

Отображение текущего имени хоста

В системах Linux, использующих systemd, команду hostnamectl можно использовать для запроса и изменения имени хоста и связанных настроек на данном компьютере.

Чтобы просмотреть текущее имя хоста, вызовите команду hostnamectl без аргументов:

Имя хоста системы выделено на изображении ниже:

Изменение имени хоста

Чтобы изменить имя хоста, вызовите команду hostnamectl с аргументом set-hostname за которым следует новое имя хоста. Только root или пользователь с привилегиями sudo может изменить системное имя хоста.

Например, чтобы изменить системное имя хоста на mail.linuxize.com , вы должны использовать следующую команду:

sudo hostnamectl set-hostname mail.linuxize.com

Команда hostnamectl не выводит данные. В случае успеха возвращается 0 , в противном случае — ненулевой код ошибки.

Наконец, чтобы убедиться, что имя хоста было успешно изменено, еще раз используйте команду hostnamectl :

Новое имя хоста системы и некоторая дополнительная системная информация, такая как версия ядра, будет отображаться на терминале.

 Static hostname: mail.linuxize.com Icon name: computer-vm Chassis: vm Machine ID: 70a3f06298014fd9ac42e5dc1de1034a Boot ID: 6d45a1a8d436418e97519da01ea61c1b Virtualization: oracle Operating System: Debian GNU/Linux 10 (buster) Kernel: Linux 4.19.0-5-amd64 Architecture: x86-64 

Выводы

В этом руководстве мы показали вам, как изменить имя хоста вашей системы Linux. В зависимости от вашего дистрибутива Linux и типа виртуализации для завершения процесса могут потребоваться дополнительные шаги.

Инструкции для конкретного дистрибутива можно найти в следующих статьях:

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Источник

Читайте также:  Смарт тв sony linux

How to Change Hostname on Ubuntu 20.04

A hostname is a user-generated custom name which identifies a computer system in a network. In Ubuntu 20.04, users assign a hostname to the machine during OS setup.

You may decide to change your computer’s hostname for several reasons. For example, no two computers on a network can have the same hostname and, if you find yourself in this situation, you will have to change the hostname to avoid a network conflict.

In this tutorial, you will learn how to change a hostname on Ubuntu 20.04 using the Linux command line or GUI.

How to Change Hostname in Ubuntu 20.04

  • Ubuntu 20.04 installed
  • An account with sudo privileges
  • Access to the command line for non-GUI methods

How to Check Current Hostname on Ubuntu 20.04

To check the current hostname of your Ubuntu system, use one of two available commands.

Checking hostname using the hostname command

  • The other command, hostnamectl , displays additional information about your computer system.

Checking hostname using the hostnamectl command

The Static hostname line displays your machine’s hostname.

Note: Valid hostnames are between 2 and 64 characters in length. They can contain only letters, numbers, periods, and hyphens, but must begin and end with letters and numbers only.

Temporarily Change Hostname on Ubuntu 20.04

Use the hostname command to make a temporary change to your computer’s hostname.

In the terminal, type the following, replacing new-hostname with the name you choose:

sudo hostname new-hostname

If successful, this step will not provide any output. To confirm the result of the process, check the current system hostname:

Changing hostname using hostname command

Change Hostname on Ubuntu 20.04 (No Reboot Required)

If you wish to permanently change the hostname without rebooting your computer, use the hostnamectl command.

Step 1: Use set-hostname to Change the Hostname

Type the following command:

hostnamectl set-hostname new-hostname

Use your own hostname choice instead of new-hostname .

Step 2: Use hostnamectl to Confirm the Change

Just like the hostname command, if successful, hostnamectl set-hostname does not produce any output. Therefore, use hostnamectl to check the result.

Changing hostname using hostnamectl set-hostname command

Step 3: Change the Pretty Hostname (Optional)

A “pretty” hostname is the hostname presented to the user, not to another computer on a network. A computer system identifies another computer only by its static hostname.

Note: The pretty hostname does not have the naming limitations of its static counterpart – any UTF-8 value is permitted.

To change a machine’s “pretty” hostname, use the same hostnamectl command with the —pretty option:

hostnamectl set-hostname "new-hostname" --pretty

Replace new-hostname with your own UTF-8 value.

After checking the result with hostnamectl , you will notice an additional line in the output, listing the computer’s “pretty” hostname.

Changing the pretty hostname using hostnamectl command with --pretty option

Note: The “pretty” hostname is stored in /etc/machine-info. Updating this file is another way to perform this optional step.

Change Hostname on Ubuntu 20.04 – Alternative Method (Reboot Required)

Another way to permanently change the hostname is by editing two configuration files:

The changes take effect immediately after system reboot.

Step 1: Open /etc/hostname and Change the Hostname

Edit the file with a text editor of your choice. In this example, we will be using the Vim editor:

The /etc/hostname file contains only the current hostname. Replace it with your new choice.

Editing the /etc/hostname file

Step 2: Open /etc/hosts and Change the Hostname

Now edit the /etc/hosts file in the same way.

Читайте также:  Open suse enterprise linux

The file /etc/hosts maps hostnames to IP addresses. Look for the hostname you wish to change and simply replace it with your new choice.

Editing the /etc/hosts file

Step 3: Reboot the System

Reboot your computer to apply the changes:

Note: If you use the Cloud-Init package ( cloud-init ) to run a cloud instance of Ubuntu, you need to perform another step before rebooting. Go to /etc/cloud/cloud.cfg file and make sure the line preserve_hostname is set to TRUE .

Change Hostname on Ubuntu 20.04 Using GUI

The Ubuntu GUI also provides a way to edit the system hostname:

1. First, navigate to Settings > About.

Navigating to the About section in Ubuntu 20.04 settings

2. Now, locate the Device Name field.

Locating the Device Name field in the About section of Ubuntu 20.04 settings

3 Clicking the Device Name field opens the Rename Device dialogue box.

4. In the Rename Device dialogue box, replace the current hostname with a new one and confirm your choice by clicking the Rename button. This action permanently changes the hostname.

Changing the Device Name in the About section of Ubuntu 20.04 settings

This article presented three methods in which you can change the hostname on your Ubuntu 20.04 machine, using the command line or GUI. All the methods are simple and straightforward, so you can choose whichever one fits your use case best.

Источник

How to Change Hostname on Ubuntu & Other Linux Distributions

The hostname is basically your computer’s name. It can be used to identify and communicate your system on the same network.

Some Linux distributions and cloud service providers let you choose the hostname while installing. Some will automatically create one for you but you’ll always have a computer name.

If you don’t like the one you’ve got, you can use the following systemd command to change hostname on major Linux distributions:

hostnamectl set-hostname new_host_name

Read the rest of the article to learn more about hostname and ways to change it.

Before you see various ways to change the hostname, you should first know what’s a hostname!

What is a hostname in Linux?

A hostname is a name assigned to a “host” i.e. a computer on a network. The hostname is basically just your computer’s name. It’s used to identify your computer on the network.

You can see the hostname in the terminal using the hostname command.

check the current hostname in terminal

As you can see in the above screenshot, the username is abhishek while the hostname is itsfoss.

When you install Ubuntu, it asks you to choose a name for your computer. That’s the “hostname” for your system.

If at any point in time you feel like your computer doesn’t have a fancy or relevant name, you can easily change the hostname in Linux.

Note that you shouldn’t use the same hostname on two different computers on the same network, as this can cause problems. This hostname is supposed to uniquely identify a computer on a network.

There are two ways to change the hostname in Ubuntu:

Here I am assuming you have Ubuntu on your system, but you can try the same command line trick on Linux Mint and some other Debian distributions as they use the same configuration as Ubuntu.

Change hostname in Ubuntu & other Linux using command line

If you want to change the hostname in Ubuntu or any other Debian based Linux distribution, you can use the typical Linux way to do that, which is using the command line.

Читайте также:  Rpm in linux pdf

Now, there are several commands for changing the hostname in Linux. I’ll show you two such methods here.

Method 1: Change hostname using systemd tools

If your Linux system uses systemd, you can use the tools provided by systemd to change the hostname. To check your current hostname and some other information, use the command:

Static hostname: itsfoss-ubuntu Icon name: computer-vm Chassis: vm Machine ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Boot ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Virtualization: kvm Operating System: Ubuntu 22.04.1 LTS Kernel: Linux 5.15.0-47-generic Architecture: x86-64 Hardware Vendor: QEMU Hardware Model: Standard PC _Q35 + ICH9, 2009_

To change the hostname, you can use this option with the hostnamectl command:

Of course, replace the with your new hostname in the above command.

changing the hostname through terminal command

Method 2: Change hostname with hostname command

Open a terminal and use the command below to change the hostname. Replace with the new hostname you want to use:

change the hostname using hostname command

Now if you use the command hostname, you’ll see that your hostname has been changed.

But the changes you just made are not permanent. If you reboot your system, the old hostname will be back.

To change your hostname permanently, you’ll also need to edit your /etc/hostname and /etc/hosts file, which is where Ubuntu, Mint and other Debian-based distributions store the hostname.

Since you are in terminal, you need to use a command line based text editor to edit these files like Vi or Vim. Ubuntu has Nano editor installed by default so you can use that as well.

I am going to use nano here. You’ll only see one line here and that contains your system’s hostname. Change it to the hostname you want and save the file.

You must also edit the /etc/hosts file in the similar fashion and replace all the occurrences of your old hostname with the new hostname.

This is important otherwise you’ll start seeing “sudo: unable to resolve host” error.

hosts and hostname files containing current hostname

Though I used Ubuntu here, you can use these methods to change hostname in Debian or most other distributions.

Change hostname in Ubuntu Using GUI

The beginner-friendly Linux distribution Ubuntu often provides the graphical way of doing things.

To change the hostname in Ubuntu 22.04 or any other Linux distribution using GNOME desktop, just go to the System Settings and click on About.

In here, you’ll see the ‘Device name’ field that is editable. This ‘Device name’ is your system’s hostname. Change it to whatever you want. The changes you make here are permanent.

change the hostname through ubuntu settings gui

It’s the same process pretty much in any other desktop environment.

Bonus Tip: Mandatory rules for hostnames

There are some rules specified for hostname:

  • hostname can only contain letters, digits, and the hyphen character, and the period character
  • hostname must begin and end with a letter or number
  • hostname must be between 2 and 63 characters long

If your proposed hostname doesn’t follow the rules, you may see an error like this:

hostname: the specified hostname is invalid

invalid hostname because of unsupported characters

In the end…

I hope this article helped you to change hostname on Ubuntu and other Linux distributions. Feel free to provide your feedback.

Источник

Оцените статью
Adblock
detector