Change machine name linux

How do I change the computer name?

Try editing /etc/ hosts. gksudo gedit /etc/hosts and replace server-name.belkin by whatever name you desire.

@warren the current consensus is to close by «quality»: meta.stackexchange.com/questions/147643/… Since «quality» is not measurable, I just go by upvotes. 😉 Likely it comes down to which question hit the best newbie Google keywords on the title.

14 Answers 14

You need to edit the computer name in two files:

These will both need administrative access, so run

Replace any instances of the existing computer name with your new one. When complete run

sudo service hostname start 

The name will also be changed if you restart your computer.

sudo service hostname restart doesn’t work on default install of ubuntu server 14.04 on AWS. I had to do full server restart

On 14.04, I simply ran sudo hostname , and that did the trick. I didn’t notice any immediate change, but when I opened a new terminal, I saw my hostname had indeed changed.

hostnamectl set-hostname on 13.10+ desktop

This is the best way if you have systemd (13.10 onwards) and if cloud-init is not active (see below):

hostnamectl set-hostname 'new-hostname' 

18.04 onwards: cloud-init

18.04 Introduced cloud-init which can control setting of the hostname so hostnamectl changes it won’t stick after a reboot if cloud-init is installed. TODO: how to check if it is installed, is it installed by default on the desktop image or just server?

If you want hostnamectl changes to stay after a reboot, then you’ll need to edit the cloud-init config files, disable cloud-init’s hostname set/update module:

sudo sed -i 's/preserve_hostname: false/preserve_hostname: true/' /etc/cloud/cloud.cfg 

or disable cloud-init entirely:

sudo touch /etc/cloud/cloud-init.disabled 

I had to add my new-hostname into /etc/hosts else using sudo would cause some error «sudo: unable to resolve host xxxxx»

Working also with Ubuntu 20 LTS as desktop, and only using sudo hostnamectl set-hostname myNewName . After new terminal and after boot (!), the` myNewName`, no problem.

  1. Edit /etc/hostname , make the name change, save the file.
  2. You should also make the same changes in /etc/hosts file
  3. Run sudo service hostname start

As long as you have no application settings depending on the ‘old’ hostname, you should be ok 😉

WARNING: If you do this without changing /etc/hosts accordingly you will be unable to use sudo because your hostname will fail to lookup

You’re right regarding editing the /etc/hosts, i forgot about it (just added it to my answer), though sudo seems to be working fine for me without changing it (i’ve restarted the machine and it still works)

It’s ok, you can do that as hostname is now a service managed from upstart . It’ll do exactly the same thing,restart the service.

Warning: won’t work with Ubuntu 18+ which is running cloud-init by default, which controls hostname on boot.

Читайте также:  Linux open ports in use

It is safe to do, you just need to be sure you edit both the system hostname configuration file (/etc/hostname) and the hostname name resolution file (/etc/hosts). From a terminal execute the following:

sudo -s editor /etc/hostname editor /etc/hosts shutdown -ry now 

Warning: won’t work with Ubuntu 18+ which is running cloud-init by default, which controls hostname on boot.

In addition to editing /etc/hosts and /etc/hostname, various services might have issues with the change as well. Mysql and postfix are installed by default in ubuntu. A broken postfix won’t affect most ubuntu users, since it’s a background email server that isn’t used by much.

sudo editor /etc/postfix/main.cf sudo service postfix restart 

The default config for mysql doesn’t use hostname, so it will work fine as-is. If you have customized it, edit the files in /etc/mysql/ and restart the service.

You may also want to edit /etc/motd (message of the day), which is shown on virtual terminals and remote logins. That one won’t harm anything though.

Other services that you may have installed that would need fixing are apache, bind9, etc. In each case, find and edit the hostname in their config and restart the service.

Источник

How to Set or Change Hostname in Linux

By default, the system hostname is set during the installation process, or if you are creating a virtual machine it is dynamically assigned to the instance at startup, but there are situations when you need to change it.

This tutorial will walk you through the process of changing the hostname in Linux without the need of restarting the system. The instructions should work on any modern Linux distribution that uses systemd.

What is Hostname #

A hostname is a label assigned to a machine that identifies the machine on the network. Each device in the network should have a unique hostname.

The hostname can be a simple string containing alphanumeric characters, dots and hyphens. If the machine is connected to the Internet (such as web or mail server) it is recommended to use a fully qualified domain name (FQDN) as a system hostname. The FQDN consists of two parts, the hostname, and the domain name.

Displaying the Current Hostname #

On Linux systems using systemd, the hostnamectl command can be used to query and change the hostname and related settings on a given machine.

To view the current hostname, invoke the hostnamectl command without any arguments:

The system hostname is highlighted in the image below:

Changing the Hostname #

To change the hostname invoke the hostnamectl command with the set-hostname argument followed by the new hostname. Only the root or a user with sudo privileges can change the system hostname.

For example, to change the system hostname to mail.linuxize.com , you would use the following command:

Источник

How to Change Hostname in Linux

To differentiate devices, data packets use IP addresses; however, IP addresses may not be easy for humans to recognize. Luckily, in Linux, the hostname is used in places like the terminal prompt to identify the device being used. In this guide, we will show you how to change the hostname of a device in Linux.

Читайте также:  Find class in jars linux

Hostname in Linux

Devices communicate with each other over a network by using IP addresses. The IP address assigned to a particular device may change depending based on the situation. Therefore, it is important to use a memorable hostname that does not change based on the situation.

Several methods can be used to change the hostname in Linux, and these methods can be divided into two categories: command-line interface (CLI) methods and graphical user interface (GUI) methods.

CLI methods

To change the hostname of a device in Linux, we recommend using CLI tools. These methods are universal and will work on almost any Linux distro. Furthermore, there is also no need to install any additional packages.

Check hostname

First, check the hostname of the current system as follows.

Change hostname using hostname

The hostname command can be used to change the hostname of the system by using the following command structure.

Finally, verify the change.

Note that the hostname in only temporarily changed using this method. If the system is rebooted, then it will revert back to the original hostname. This method should be used only when you do not intend to make a permanent hostname change.

Change hostname using hostnamectl

The hostnamectl tool is controls the hostname of the system. This tool can perform a wide range of actions; for example, it can be used to show the current hostname, to change the hostname, to configure the environment description, and to manipulate the system LOCATION string.

To use hostnamectl to change the hostname, run the following command.

Next, we have to manually update the host file. To do so, open the file using a text editor.

Change the old hostname to the new hostname.

If you are using an older Linux distro, then after making the change, you may need to run the following command.

Change hostname (for init system)

A dedicated file holds the hostname of the system. We can manually update the file to change the hostname. To do so, open the file using a text editor.

The image below shows the old hostname.

Edit the content to update the hostname.

Save the file and close the editor. For the changes to take effect, reboot the system. After the system reboots, verify that the action was successful as follows.

GUI Methods

In this section, we will use GNOME to change the hostname of a device. However, you can use YaST to perform hostname changes in openSUSE.

Change hostname in GNOME

GNOME is a powerful desktop environment. If you use GNOME, then you can change the hostname without running any commands by accessing the “Settings” app.

From the left panel, scroll to the bottom and select “About”. In this example, the hostname of the system is in the “Device name” field.

Click “Device name” to open a prompt for changing the hostname.

Enter the new hostname and click “Rename” to save the change.

Final thoughts

In this tutorial, we showed you several simple methods for changing the hostname of your system. Make sure to use a proper hostname to help to identify the system.

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

If you are using CentOS/RHEL or a similar distro, then changing the hostname may be more difficult. Check out how to change hostname permanent on CentOS 7.

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

Как изменить имя компьютера Ubuntu

Имя компьютера или по-другому, имя хоста устанавливается во время установки системы. Оно используется для идентификации компьютера в локальной сети, например, передается службой NetBIOS как имя сервера Samba, а также вы будете постоянно видеть его в терминале перед приглашением ввода команды.

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

Требования к имени компьютера

Вы можете использовать практически любое имя компьютера, но для него есть некоторые ограничения. Не желательно использовать два одинаковых имени компьютера в одной локальной сети, иначе могут возникнуть проблемы с различными интернет-сервисами и самая очевидная — вы не сможете понять где какой компьютер.

Второе ограничение — имя компьютера может содержать только буквы английского алфавита от a до z, цифры от 0 до 9, а также символы дефиса и точки. Начинаться и заканчиваться имя должно только буквой или цифрой, а не символом подчеркивания. Имя хоста регистронезависимо, поэтому COMPUTER и computer будут означать одно и то же. По длине стоит ограничение от 2 до 69 символов, но этого вполне достаточно.

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

Посмотреть текущее имя компьютера можно выполнив команду hostnamectl без параметров:

Изменить имя хоста Ubuntu можно несколькими способами. Самый простой способ установить имя компьютера, которое сохранится только до перезагрузки можно использовать команду hostname, которой в параметре нужно передать новое имя. Например:

Но после перезагрузки все вернется как было раньше. Чтобы сделать изменения постоянными нужно изменить содержимое двух файлов. /etc/hostname и /etc/hosts:

Удалите старое имя из этого файла и пропишите новое. Затем сохраните изменения.

В современных версиях Ubuntu вы можете использовать команду hostnamectl, в отличие от первого варианта изменения сохранятся после перезагрузки:

sudo hostnamectl set-hostname новое_имя

Затем откройте второй файл:

Здесь немного сложнее, найдите строку:

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

systemctl restart systemd-logind.service

Теперь все должно работать правильно. Но это не единственный способ сменить имя хоста в Ubuntu.

Не меняется имя компьютера

Если вы поменяли имя компьютера, а после перезагрузки восстанавливается все как было, например, какое-то там dhcpcd0-pc, то, скорее всего, виноват NetworkManager. Здесь решение либо удалить эту программу, либо изменить имя хоста Ubuntu с помощью NetworkManager. Для этого выполните:

sudo vi /etc/NetworkManager/NetworkManager.conf

И добавьте в файл такие строки:

Теперь после перезагрузки NetworkManager поменяет имя хоста Ubuntu на правильное и больше проблем с этим не будет.

Выводы

Вот и все, теперь вы знаете как сменить имя компьютера Ubuntu. Для этого есть вполне достаточно способов, чтобы вы могли выбрать именно то, что нужно. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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