Linux hostname etc hostname

Как поменять имя хоста (hostname) в Linux ?

Имя хоста (или hostname) — это уникальное имя, которое идентифицирует компьютер в сети. В Linux, имя хоста хранится в файле /etc/hostname . Если вы только что установили операционную систему Linux, то имя хоста будет установлено по умолчанию, но вы можете легко изменить его, следуя простым шагам в этой статье.

Шаг 1: Проверьте текущее имя хоста

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

Эта команда выведет имя текущего хоста. Если вы работаете в удаленной среде, например, через SSH, то имя хоста будет отображаться в приглашении командной строки перед символом @ .

Шаг 2: Отредактируйте файл /etc/hostname

Теперь мы можем изменить имя хоста, отредактировав файл /etc/hostname . Для этого введите следующую команду в терминале:

Эта команда откроет файл /etc/hostname в текстовом редакторе Nano. Замените текущее имя хоста на новое и сохраните изменения, используя сочетание клавиш Ctrl+X , затем Y , затем Enter .

Обратите внимание, что новое имя хоста должно состоять только из букв, цифр и дефисов. Также, оно не должно быть длиннее 64 символов.

Шаг 3: Измените имя хоста в файле /etc/hosts

Теперь мы должны изменить имя хоста в файле /etc/hosts . Для этого введите следующую команду в терминале:

Найдите строку, которая начинается с 127.0.0.1 и содержит старое имя хоста. Замените старое имя на новое и сохраните изменения, используя сочетание клавиш Ctrl+X , затем Y , затем Enter .

Также, если ваш компьютер используется в локальной сети, то в файле /etc/hosts могут быть указаны и другие компьютеры с их именами хостов. В этом случае, вам нужно будет обновить информацию об имени хоста в этих строках.

Шаг 4: Перезагрузите компьютер

Чтобы изменения вступили в силу, перезагрузите компьютер. Для этого введите следующую команду в терминале:

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

Заключение

Теперь вы знаете, как изменить имя хоста (hostname) в Linux. Это может быть полезно, если вы хотите изменить имя компьютера в сети или просто избавиться от имени хоста, которое было установлено по умолчанию. Кроме того, помните, что имя хоста используется не только для идентификации компьютера в сети, но и для многих других задач, таких как настройка DNS, конфигурация почтового сервера и т.д. Поэтому, если вы не уверены в том, как изменение имени хоста повлияет на работу вашей системы, лучше проконсультируйтесь с опытным администратором.

Читайте также:  Linux сочетание клавиш перезагрузка

Источник

Как изменить Hostname (имя компьютера)

Как изменить Hostname

Hostname (имя компьютера, имя хоста) задается во время установки системы Linux. Hostname определяет название компьютера и используется преимущественно для идентификации компьютера в сети. Нельзя назначать два одинаковых Hostname для компьютеров в одной сети.

Просмотр текущего Hostname

Чтобы показать текущий Hostname можно использовать команду hostname без параметров:

Также Hostname можно отобразить командой hostnamectl :

Как изменить Hostname

Рассмотрим, как изменить Hostname двумя разными способами.

Способ 1. Используем команду hostnamectl

Во многих systemd-based дистрибутивах (например, в Ubuntu Linux) есть утилита hostnamectl .

Воспользуемся командой hostnamectl , чтобы установить новое значение Hostname равным pingvinus . Используется аргумент set-hostname:

sudo hostnamectl set-hostname pingvinus

Способ 2. Редактируем файлы /etc/hostname и /etc/hosts

Еще один способ изменения Hostname — это ручное редактирование файла /etc/hostname и файла /etc/hosts .

Сначала выполните команду (вместо pingvinus укажите свое значение):

Отредактируем файл /etc/hostname для редактирования в редакторе nano, выполняем команду:

Измените текущее значение в файле на новое. Сохраните изменения и закройте файл. Это можно сделать, нажав Ctrl+C , затем Y и Enter .

Hostname прописывается также в файле /etc/hosts , поэтому нужно изменить его значение в этом файле. Откроем файл:

Найдите строку вида « 127.0.0.1 ваш_hostname » и впишите новое имя хоста. Сохраните изменения и закройте файл.

Проверка результата

Чтобы проверить, изменилось ли значение Hostname, откройте новое окно терминала и введите команду:

Как временно изменить Hostname

Чтобы изменить Hostname в текущей работающей системе Linux, но до первой перезагрузки, можно использовать просто команду hostname , указав ей новое значение имени хоста:

Источник

How to Set or Change Hostname in Linux? [Linux Change Hostname]

How to Set or Change Hostname in Linux? [Linux Change Hostname]

To identify hosts or servers in a network, each Linux server is assigned a name called host-name. It’s simply a name given to your Linux machine. When you install any Linux distribution, it will ask you to enter a username and a hostname for the first time. At any point in time, if you wish to change the hostname for any purpose, you can easily do so in just a few steps. However, please note that you should never assign the same hostname to multiple Linux servers in the same network.

There are some rules when it comes to what name can you assign as a hostname to a server in the network. A hostname can contain digits, lowercase letters, hyphens, and dots. But please make sure that a hostname must start and end with either a number or a letter. They must contain at least 2 characters and at most 63 characters.

Читайте также:  Линукс настройка прокси сервер

How to Display Current Linux Hostname with hostname command?

When you open a terminal, you will find the following structure at the beginning of every Linux terminal command.

To display the current hostname in the terminal, you can use the hostname command.

The Linux OS also stores the current hostname in a separate file inside the etc directory — /etc/hostname. You can use the cat or less command to display the contents of this file which will give you the hostname.

How to change Linux hostname for various Linux distros?

1. How to change hostname in Ubuntu/Debian-based Distros?

If you own a Debian-based Linux distribution such as Ubuntu, Linux-Mint, etc., you can use either a command-line method or a GUI-based method to change Linux hostname. We will discuss two methods to change hostname using the command line in this article.

Method 1. Using systemd tools

We can use systemd tools to change the hostname along with some other similar type of information. Let’s use the following command first to get the current information.

You can see information such as hostname, OS, kernel, Machine ID, Boot ID, etc.

We can use the following hostnamectl command to change your current username.

You can see that the static hostname has been changed successfully. If you restart your terminal, you will see the changes reflected there as well.

Method 2. Using hostname command with example

You can also use the hostname command to change your hostname in Debian-based Linux Distributions.

You will need Sudo privileges to use this command. Restart the terminal to see the changes. However, using this command, the changes will be made temporarily. This means that once you restart your machine, the old hostname will be restored.

If you want to change your hostname permanently, you need to make the required changes in the following files — /etc/hostname and /etc/hosts. These are the two files where the Debian-based Linux distros stores information related to the hostnames. We can edit these files straight through the command line using editors such as vim and nano.

$ vi /etc/hostname
$ vi /etc/hosts

Once you have made changes to these files, it will be done permanently.

2. How to Change hostname in CentOS/RHEL 7 or 8?

If you use a Redhat-based Linux Distribution like CentOS, you can use the following three methods to change your hostname.

Method 1.

You can use the same hostnamectl command that we used for Debian-based Linux distributions to change the hostname in Redhat-based Linux distros as well. In fact, this command holds true for all Linux distros that use systemd.

First, let’s display the current hostname using any of the following commands.

Читайте также:  Kaspersky linux web server

# hostname
# hostname -s
# hostname -f
# cat /etc/hostname
#hostnamectl

The second command uses the -s option which tells the command to print only the short name or the hostname of the computer. The -f option will print the FQDN if it’s a part of a domain. The next command will print the contents of the hostname file which stores the hostname of the Linux machine. We can additionally use the hostnamectl command to print the hostname.

We can now use the following command to change the hostname in CentOs 7, 8, or any other Redhat-based Linux Distro.

Now, to apply these changes, just reboot the system using the following command.

Method 2.

You can also edit the file called /etc/hostname and write your new hostname on any CentOS machine.

Just reboot the system again to see the changes.

Method 3.

The Linux Kernel maintains a transient hostname as an auxiliary server name along with the conventional static hostname. We can use the Linux sysctl to change the transient hostname.

You can use the above command to display the current transient hostname.

# sysctl -w kernel.hostname=new-hostname

The above commands can also be used to set a new hostname.

Wrapping Up!

In this comprehensive guide, we started with a basic introduction to discuss what are hostnames in Linux machines and what purpose do they serve. We also discussed a few methods that we can use to display the current hostname in Linux servers. We then discussed a general method that can be used to change the hostnames in any type of Linux Distribution whether Debian-based, RHEL-based, etc. We then discussed separate methods to change the hostnames in Debian-based distributions such as Ubuntu, Linux Mint, etc. We can also set the hostnames using a GUI-based method by moving to the user settings. We also discussed a few methods to change the hostname for RHEL-based distributions such as CentOS 7, 8, etc.

There might be several reasons why you would want to change Linux hostname of your device in a network. Regardless of all those reasons, changing Linux hostnames is quite easy and can be done in just a few steps only. We hope that this comprehensive guide serves its purpose and you can now change your hostnames easily. also if you are looking to buy a Linux server you can opt for MonoVM as the best Linux server provider.

People Are Also Reading:

Источник

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