Как изменить имя компьютера в Linux
Если вам понадобилось изменить имя на вашем сервере/персональном компьютере/еще чем-то, и это что-то работает под Linux, то сделать это можно следующими способами:
Смена имени через команду и файл hostname
Если целью стоит быстрая смена имени, то для этой цели вполне может подойти команда hostname. Просто пишем следующую команду:
hostname НОВОЕИМЯ
где НОВОЕИМЯ – это новое имя. Смена имени устройства произойдет сразу же как только вы выполните эту команду. Однако, как только произойдет перезагрузка, то имя компьютера сменится на то, что прописано в текстовом файле /etc/hostname. Поэтому, для постоянной смены имени компьютера, нужно отредактировать так же данный файл, изменив его содержимое на новое имя компьютера. После этого, даже после перезагрузки, у компьютера будет нужное вам имя.
Смена имени через sysctl
В новых дистрибутивах Linux, таких как Debian 8, Ubuntu 16 и т. д, быструю смену имени устройства можно осуществить с помощью команды sysctl kernel.hostname . Достаточно лишь выполнить команду:
sysctl kernel.hostname=НОВОЕИМЯ
где вместо НОВОЕИМЯ нужно указать желаемое имя. После этого нужно будет просто перелогиниться на устройство, и будет отображаться новое имя.
Смена имени через hostnamectl
Начиная с 7 версий таких дистрибутивов как CentOS и Red Hat Enterprise Linux (а так же в некоторых других, например Ubuntu), в них стала возможна смена имени устройства с помощью команды hostnamectl. Для этого данная команда используется следующим образом:
hostnamectl set-hostname НОВОЕИМЯ
конечно же не забыв поменять НОВОЕИМЯ на нужное вам. После выполнения команды все, что остается, это перезагрузить сервис systemd-hostnamed для применения изменений:
systemctl restart systemd-hostnamed
Managing Linux: Change Hostname Tutorial
A hostname is a name used to identify a device on a network. Usually, it is set as localhost during the operating system installation.
However, if there are several devices in a network, this might generate duplicates and cause network conflict. To avoid that, it’s advised to change the hostname of your Linux system.
In this article, we will illustrate three methods to change the hostname on CentOS and other Linux distributions like Debian, Ubuntu, and Red Hat Enterprise Linux (RHEL).
How to Change Current Hostname Permanently on Linux Servers
In this section, you’ll learn how to change the current hostname permanently on Linux old or new virtual private servers – using the hostnamectl command, nmtui, or editing your configuration files.
Pro Tip
If you’re just starting, you’ll find all the instructions on how to set up VPS in our step-by-step guide.
Option 1. Using the hostnamectl Command
Modern Linux distributions come with systemd, a system and service manager that has the hostnamectl command installed by default to manage and change hostnames.
Here’s how to change your current hostname using hostnamectl:
- Open the terminal.
- Log in to your Linux server via SSH.
- If your system doesn’t have systemd, use this command to install it and press Enter:
apt-get install systemd
- Once the installation is complete, type the following command to view the current hostname and hit Enter:
hostnamectl
- Here’s how the output looks like:
Static hostname: hostinger Icon name: computer-vm Chassis: vm Machine ID: 45598cbdb6ee462e8696166b520fe788 Boot ID: 99526e56aeea45c2a0f3b2ffaaffe9d9 Virtualization: openvz Operating System: Ubuntu 20.04.3 LTS Kernel: Linux 5.4.0 Architecture: x86-64
- On the output, the current hostname is listed as the static hostname. To change it permanently, insert the following command – using your new desired hostname – and hit Enter:
hostnamectl set-hostname hostname
- The command above does not produce an output. Therefore, to verify the new hostname, run the command below and press Enter:
hostnamectl
The output will show you the new hostname.
Option 2. Using the Network Manager Text User Interface (nmtui)
The Network Manager Text User Interface (nmtui) is a text user interface that lets you configure the network and hostname in a terminal window. It is available in various Linux distributions, including CentOS and RHEL.
Here’s how to change the hostname using the nmtui command:
- Open the terminal and connect to your account via SSH.
- Install the NetworkManager-tui package by inserting the following command and hitting Enter:
sudo yum install NetworkManager-tui
- The package and list of dependencies will be loaded. Type y and press Enter to start the installation process.
- The Complete! line will appear once the nmtui package has been successfully installed.
- Run this command to check the status of the network manager and press Enter:
service NetworkManager status
- To start the nmtui service, type the following command and hit Enter:
service NetworkManager start
- Next, type this command and click Enter:
sudo nmtui
- On the NetworkManager TUI window, select Set system hostname and press Enter.
- Type the desired hostname and choose OK.
You’ve successfully changed the hostname.
Option 3. Edit the Configuration Files
The next option is editing the configuration files – /etc/hostname and /etc/hosts. Here’s how to do it:
- Open the terminal and connect via SSH.
- Open the /etc/hostname file and replace the old hostname with the new one:
vi /etc/hostname hostinger
- Next, update the hostname record in the /etc/hosts file so that the system resolves the new hostname in the network.
# vi /etc/hosts 127.0.0.1 hostinger
At this point, you finished updating the records in the configuration files. However, to apply the changes, you’ll need to edit the cloud configuration file.
Here’s how to do it:
- Open the cloud configuration file by inserting this command on the terminal and pressing Enter:
sudo vim /etc/cloud/cloud.cfg
- Change the value of the following line to true:
preserve_hostname: true
- Reboot your system and open the terminal. To verify if the hostname was indeed preserved during the reboot, run the following command and hit Enter:
hostname
This will display the new hostname you have set up.
Important! If the cloud configuration file is not available in your system, you can safely skip these steps.
How to Change Hostname Without Rebooting
In this section, you’ll learn how to change the hostname without rebooting the system. However, as soon as you restart the system, it will revert to the old hostname.
This method is useful when you need to complete a minor task that requires temporary changes. The basic syntax of the command is:
hostname [new_host_name]
Here’s how to use it:
- On the terminal, type the hostname command along with the new hostname and hit Enter.
hostname hostinger
- Verify if the hostname has been set correctly by inserting the following command and pressing Enter:
hostname
The output will display the updated hostname.
How to Change Linux Hostname Permanently on Hostinger VPS
If you use Hostinger VPS, the only way to change the hostname permanently is through the hPanel. Here’s how to do it:
- Go to the VPS tab and select server you want to change.
- Select Settings on the left sidebar.
- Scroll down and type the new hostname in the Change Hostname box. Click Save.
Your virtual hosting server, your rules. Get all the resources you need for your next project. Get VPS Hosting
Conclusion
The system hostname is an essential part of a Linux server as it helps identify your machine within a network.
Most Linux systems provide tools and commands so users can customize the system hostnames to their preferences. We shared three methods to change hostnames based on your needs:
- Running the hostnamectl command, using nmtui, or editing the hosts file to change the hostname permanently.
- Using the hostname [new_host_name] command to change the hostname temporarily and without rebooting the system.
- Changing Linux hostname permanently on Hostinger VPS via the hPanel.
We hope this article has helped you set up a new hostname in your Linux system. If you have any questions or suggestions, please share them in the comment section below.
Learn More About Your VPS
The author
Edward is a content editor with years of experience in IT writing, marketing, and Linux system administration. His goal is to encourage readers to establish an impactful online presence. He also really loves dogs, guitars, and everything related to space.
The Co-author
Noviantika is a web development enthusiast with customer obsession at heart. Linux commands and web hosting are like music to her ears. When she’s not writing, Noviantika likes to snuggle with her cats and brew some coffee.
Как изменить Hostname (имя компьютера)
Hostname (имя компьютера, имя хоста) задается во время установки системы Linux. Hostname определяет название компьютера и используется преимущественно для идентификации компьютера в сети. Нельзя назначать два одинаковых Hostname для компьютеров в одной сети.
Просмотр текущего Hostname
Чтобы показать текущий Hostname можно использовать команду hostname без параметров:
hostname
Также Hostname можно отобразить командой hostnamectl :
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 укажите свое значение):
sudo hostname pingvinus
Отредактируем файл /etc/hostname для редактирования в редакторе nano, выполняем команду:
sudo nano /etc/hostname
Измените текущее значение в файле на новое. Сохраните изменения и закройте файл. Это можно сделать, нажав Ctrl+C , затем Y и Enter .
Hostname прописывается также в файле /etc/hosts , поэтому нужно изменить его значение в этом файле. Откроем файл:
sudo nano /etc/hosts
Найдите строку вида « 127.0.0.1 ваш_hostname » и впишите новое имя хоста. Сохраните изменения и закройте файл.
Проверка результата
Чтобы проверить, изменилось ли значение Hostname, откройте новое окно терминала и введите команду:
hostname
Как временно изменить Hostname
Чтобы изменить Hostname в текущей работающей системе Linux, но до первой перезагрузки, можно использовать просто команду hostname , указав ей новое значение имени хоста:
hostname новое_имя
При подготовке материала использовались источники:
https://pc.ru/articles/kak-izmenit-imya-kompyutera-v-linux
https://www.hostinger.com/tutorials/linux-change-hostname
https://pingvinus.ru/note/change-hostname