Ubuntu how to change hostname
Ubuntu how to change hostname
How To Change Hostname on Ubuntu & Other Linux Distributions
In this quick tutorial, I’ll show you how to change hostname on Ubuntu, Debian and other Linux distributions.
How to Change hostname in Linux
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 on 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.
As you can see in the above screenshot, the username is abhishek while the hostname is istfoss-notes.
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 of the time you feel like your computer doesn’t have a fancy or relavant 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 problem. This hostname is supposed to uniquely identify a computer on a network.
There are two ways to change hostname in Ubuntu:
We shall see both ways of changing the hostname in this tutorial.
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 distribution 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.
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:
It’s output should be something like this:
Static hostname: itsfoss
Icon name: computer-laptop
Chassis: laptop
Machine ID: 1b9ab93094fa4978beba80fd3c48a18c
Boot ID: 68a0f4c77b9d4ca3aaa2c99ce051a7f8
Operating System: Ubuntu 18.04.2 LTS
Kernel: Linux 4.15.0-46-generic
Architecture: x86-64
To change the hostname, you can use this option with the hostnamectl command:
Of course, replace the with your new host name in the above 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:
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 the 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.
That’s it. You are done!
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 18.04 or any other Linux distribution using GNOME desktop, just go to the System Settings and click on Details.
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.
It’s the same process pretty much in any other desktop environment. If you are using Ubuntu 16.04 Unity you can expand the next section to see the screenshots.
To change the hostname, go to System Settings (search for it in Unity Dash or GNOME). In here, look for Details.
Here, you’ll see the option to change the name. You don’t need to save it explicitly:
Bonus Tip: Mandatory rules for hostnames
There are some rules specified for hostname:
If your proposed hostname doesn’t follow the rules, you may see an error like this:
In the end…
I hope this article helped you to change hostname on Ubuntu and other Linux distributions. Feel free to provide your feedback.
Creator of It’s FOSS. An ardent Linux user & open source promoter. Huge fan of classic detective mysteries ranging from Agatha Christie and Sherlock Holmes to Detective Columbo & Ellery Queen. Also a movie buff with a soft corner for film noir.
Ubuntu Documentation
Introduction
You can configure a network interface from the command line. You can configure your network client hosts with the command line by using commands to change your current settings or by editing a number of system files. This has several advantages over network managers in the GUI.
This guide had been developed for Ubuntu and Debian, other distributions can use a similar setup, but be aware that file locations may differ.
Requirements
An editor. This guide will use vi, but you can replace it with any other editor of your liking, gedit, nano, gvim, pico, emacs..
Have a working internet connection during the installation. We need to install packages and those are fetched from the online repositories.
Backup any files we touch. Just easier to recover when you have a backup.
Read this guide in full before actually configuring your network.
Basics
Setting/changing the hostname
The hostname command allows you to directly query, or set, the hostname from the command line.
You can see your current hostname by running hostname. To set the hostname directly you can run hostname newname as root. If you do this however, make sure you change the /etc/hosts file first. This is needed because otherwise you will need to boot into single user mode and change your hostname in /etc/hosts. This is because sudo requires DNS lookups in certain cases and it cannot resolve your newly set hostname.. To circumvent this you need to add the new name to the hosts file prior to setting the hostname and remove it once that action has succeeded.
Set the hostname to newname.
Now you can remove the old hostname
When your system boots it will automatically read the hostname from the file /etc/hostname. You can add hostname and IP addresses to the file /etc/hosts for static lookups.
Finding your network interface
When setting up your network you will need to know the network interface cards on your computer. The interface name of cards for different vendors may be different, which is why this step is needed.
This will list the interface names for all NICs on your computer. It will probably include eth0 (hardwired NIC), lo (loopback interface for the localhost), and something for your wireless card (like wifi0, or wlan0).
Disable network managers and/or wicd
Configuring your network via the CLI will likely interfere with Network Manager or wicd. To counter this, disable the startup script of either application or completely remove the packages. Be aware that the rest of this guide will require packages which need to be installed from the online repositories.
Note: At some point Ubuntu started using upstart instead of the /sbin/init/ daemon. Thus if the first command above does not stop Network Manager, try this.
Configuring an interface
We will use eth0 in this example, your interface can be named differently, see Finding your network interface.
If you have disabled the either wicd or the network manager you probably don’t have a network connection anymore. Connect via a regular UTP cable to your router, and assuming you have DHCP enabled do the following:
This will bring your eth0 up by using DHCP. Your network is now configured (for the time being).
If you don’t have DHCP enabled configure your network by issueing the commands below, the gateway address is the IP address of your router. And your IP should be in the same range as the router is.
These commands configure your interface but these changes will not survive a reboot, since the information is not stored anyhwere. This is where the interfaces file comes in handy. To configure a interface permanently you’ll need to edit the interfaces file, /etc/network/interfaces.
For these settings to take effect you need to restart your networking services.
Setting up a second IP address or Virtual IP address
If you need to set up a second ip address you need to edit the /etc/network/interfaces.
For these new settings to take effect you need to restart networking services using the following command
Howto set MTU for a connection
You can set the MTU for an interface, you could do this by using the mtu keyword in the interface file or by using the ip link command.
The above example sets the MTU for device eth0 to 1492, the usual MTU for a PPPoE ISP connection. This however is only needed if connections seem to hang otherwise (with the default of 1500).
Setting up DNS
To cause your machine to consult with a particular server for name lookups you simply add their addresses to /etc/resolv.conf.
For example a machine which should perform lookups from the DNS server at IP address 192.168.1.1 would have a resolv.conf file looking like this
enter the following details
Wireless
We will not use un-encrypted wireless connections, but will make use of WEP/WPA/WPA2. Deviations from security/encryption method is an exercise left for the user. We also assume the network SSID is being broadcast.
Enabling wireless networking on your PC is pretty straight forward. If your network card is supported out of the box, then there are very little issues. If your card is not supported out of the box, you may need to use ndiswrapper, which will require the Windows drivers fo your card.
ndiswrapper
More information about ndiswrapper
Configure your wireless interface
In the examples I will use wlan0 as your wireless card, this could be different on your machine! I will do the examples with a dynamic IP address (DHCP), the same principles applies to staticly configured IP’s.
Open the interfaces file
The pre-up command is run before the interface goes up. The post-down command is run after the interface goes down. There are also post-up and pre-down commands. E.g. You could use post-up to mount disks after an interface goes up. In this case we start wpa_supplicant before we enable the interface and we stop wpa_supplicant after we bring the interface down.
WPA supplicant
Creating the password
You probably have given your wireless network a name (the ESSID or SSID), in this example we will use ubuntuwifi for our wireless network, our password will be OpenSesame. The SSID and password needs to be configured on your wireless router, how to do that is up to the reader. If you have problems coming up with a password, please have a look here.
If you are using WEP encryption (which is not advised) you may skip this step.
Adding your network
Open the /etc/wpa_supplicant file and define your network.
Please beware, if you use WPA, remove the WEP section and vice versa.
The priority in this file determines to which network you will connect if more then 2 configured networks are available. This will always be the network with the highest priority.
WPA start script
Create the WPA startup script /etc/init.d/wpa.sh
Make the start script executable.
You can now start WPA supplicant as a service or in debugging mode:
Make sure the script gets run on boot and stopped at shutdown
With wpa_cli you can make changes to your wpa_supplicant config file and reload these changes:
Enter help to see what you can do with wpa_cli. Some of the options are: reconfigure, disconnect, reconnect, reassociate. These options speak for themself.
For more information about wpa_supplicant, please have a look at their respective manpages:
Now that you have setup everything, you can try to connect to your network by restarting networking
You could also reboot your machine if you prefer that.
Configure laptops for multiple locations
When you have a laptop you don’t want to configure it to only be able to have a internet connection at only one location. You probably go to work and use a wired connection, you goto to coffeeshop and use the wifi hotspot overthere and at home you have another network configuration. That is exactly what we are going to configure now.
Guessnet, ifplugd and wpa_supplicant
Some cards do not really play well with the defaults of Ubuntu, adjust where needed. More information for ifplugd
See ifplugd for more information. And their respective man pages
You will need the wpa.sh script mentioned earlier in this guide and you will need to make sure it will be started and stopped:
Map your physical interfaces to logical interfaces
First, we are going to make a mapping for eth0 and wlan0 and said which mapped interface could be used for each physical interface:
Normally ifupdown configures the interfaces, but now we’ve told it to use guessnet to determine the network being used.
Define tests to select networks
As you will see with the officelan, homelan and aruba examples below we will execute tests to see wheter a peer is present based on the MAC address. The simplest solution for this is to check whether your gateway is present. You can find out the MAC address of your gateway by running the ip neigh command. You need to be connected with your network for this.
This my default gateway, has IP address 192.168.1.254 and 00:24:17:47:xx:xx as a MAC address. This gives us the needed information to define the test.
You don’t need to specify the source IP address, but in certain cases this is required. I always add it so I don’t have to worry about it in case I do need it.
So let’s define our fixed networks using the peer tests:
For wireless networks you can also use the peer test, but there is a simpler way to see if you can connect to a wireless network. Test to see if the ESSID is present:
Spaces in the ESSID In older versions of guessnet you didn’t need to use quotes around the ESSID, but later versions do require it.
To see what kind of other test you can run to determine which network you are in, please have a look at the manpage of guessnet.
Use of metrics
Some of you might have noticed a metric statement for some of the interfaces. I do this because when you are connected via both wireless and wired networks, some things may go «bad» with the routing table. When you define a metric for these two interfaces you will tell the routing table which interface has preference over the other. The lowest metric has priority over the higher metric.
Or as I explained in a ubuntuforum post: The problem is that without the metric you will have 2 interfaces used for the same destinations. It will use either interface, which causes problems with the routing table.
By setting a metric you can avoid this, since the higher metric is more «expensive» to use. So the OS will use the interfaces with the lowest metric if it needs to route traffic. In case the lower metric interface is shutdown it will use the higher metric interface since it is the only interface which can be used to route traffic towards that particular network/destination.
The problem could also be solved by adding static routes, but that is used mostly to make sure specific networks/hosts are routed via a different interface then the default. You then force only those hosts to use link B even though normally the OS would use link A.
Result
When we put all the configuration segments together you will get a interfaces file which looks like this
You can now test if it all works like intended.
If you enter ip addr you will only see the lo interface being active.
And start all the required daemons:
And now you will see your interfaces configured properly
Bonus script
This script will be a stop/start script for your complete network, which can be used when you want to enable networking after you have suspended your laptop or for other reasons
See also
Ubuntu resources
External resources
NetworkConfigurationCommandLine/Automatic (последним исправлял пользователь peter-hentrich 2015-07-18 12:02:04)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Как изменить имя хоста в Ubuntu 18.04
How to Change Hostname on Ubuntu 18.04
Это руководство проведет вас через процесс изменения имени хоста в системе Ubuntu 18.04.
Имя хоста устанавливается во время установки операционной системы Ubuntu или, если вы запускаете виртуальную машину, оно динамически назначается экземпляру при запуске.
Метод, описанный в этом руководстве, будет работать без перезапуска системы.
Хотя это руководство написано для Ubuntu 18.04, те же инструкции применимы для Ubuntu 16.04 и любого дистрибутива на основе Ubuntu, включая Linux Mint и Elementary OS.
Введение
Показать текущее имя хоста
Чтобы просмотреть текущее имя хоста, введите следующую команду:
Изменить имя хоста
Следующие шаги описывают, как изменить имя хоста в Ubuntu 18.04.
1. Измените имя хоста с помощью hostnamectl
2. Отредактируйте /etc/hosts файл
Откройте /etc/hosts файл и измените старое имя хоста на новое.
3. Отредактируйте cloud.cfg файл
Если cloud-init пакет установлен, вам также необходимо отредактировать cloud.cfg файл. Этот пакет обычно устанавливается по умолчанию в образах, предоставляемых поставщиками облачных услуг, такими как AWS, и используется для обработки инициализации экземпляров облака.
Чтобы проверить, установлен ли пакет, выполните следующую ls команду :
Если вы видите следующий вывод, это означает, что пакет не установлен и никаких дальнейших действий не требуется.
Если пакет установлен, вывод будет выглядеть следующим образом:
В этом случае вам нужно будет открыть /etc/cloud/cloud.cfg файл:
Найдите preserve_hostname и измените значение с false на true :
Сохраните файл и закройте редактор.
Проверить изменение
Чтобы убедиться, что имя хоста было успешно изменено, еще раз используйте hostnamectl команду:
Вы должны увидеть ваше новое имя сервера, напечатанное на консоли.
Вывод
В этом руководстве мы показали вам, как легко изменить имя хоста сервера Ubuntu без перезагрузки компьютера.
Как изменить имя хоста в Ubuntu 20.04
Имя хоста задается во время установки операционной системы или динамически назначается виртуальной машине при ее создании.
В этом руководстве объясняется, как установить или изменить имя хоста в Ubuntu 20.04 без перезагрузки системы.
Общие сведения об именах хостов
Имя хоста — это метка, которая идентифицирует устройство в сети. У вас не должно быть двух или более машин с одинаковым именем хоста в одной сети.
Рекомендуется использовать полное доменное имя ( FQDN ), например host.example.com как для static и для transient имен.
Только root или пользователи с привилегиями sudo могут изменять системное имя хоста.
Отображение текущего имени хоста
Чтобы просмотреть текущее имя хоста, вызовите команду hostnamectl без аргументов:
Изменение имени хоста системы
Изменение имени хоста системы — простой процесс. Синтаксис следующий:
При желании вы также можете установить красивое имя хоста:
hostnamectl не производит вывода. В случае успеха возвращается 0, в противном случае — ненулевой код ошибки.
Вы не должны использовать одно и то же имя хоста на двух разных машинах в одной сети.
Если файл существует в вашей системе, откройте его:
Найдите preserve_hostname и измените значение с false на true :
Сохраните файл и закройте редактор.
Проверить изменение
Чтобы убедиться, что имя хоста было полностью изменено, введите команду hostnamectl :
Ваше новое имя хоста будет напечатано на терминале:
Выводы
Мы показали вам, как легко изменить имя хоста при установке Ubuntu 20.04 без перезагрузки компьютера.
Существует ряд причин, по которым вам может потребоваться изменить имя хоста. Чаще всего это когда имя хоста устанавливается автоматически при создании экземпляра.
Не стесняйтесь оставлять комментарии, если у вас есть вопросы.
How to Change Hostname on Ubuntu 20.04
Posted Jun 19, 2020
The hostname is set during the installation of the operating system or dynamically assigned to the virtual machine when it is created.
This guide explains how to set or change the hostname on Ubuntu 20.04 without needing to restart the system.
Understanding Host Names #
A hostname is a label that identifies a device on a network. You shouldn’t have two or more machines with the same hostname, on the same network.
In Ubuntu, you can edit the system hostname and related settings using the hostnamectl command. This tool recognizes three different classes of hostname:
It is recommended to use a fully-qualified domain name ( FQDN ) such as host.example.com for both static and transient names.
Only root or users with sudo privileges can change the system hostname.
Displaying the Current Hostname #
To view the current hostname, invoke the hostnamectl command without any argument:
Changing the System Hostname #
Changing the system hostname is a simple process. The syntax is as follows:
Optionally you can also set the pretty hostname:
hostnamectl does not produce output. On success, 0 is returned, a non-zero failure code otherwise.
You shouldn’t use the same hostname on two different machines on the same network.
If you are running Ubuntu on a cloud instance and the cloud-init package is installed, you also need to edit the /etc/cloud/cloud.cfg file. This package is usually installed by default in the images provided by the cloud providers, and it is used to handle the initialization of the cloud instances.
If the file exists on your system open it:
Save the file and close your editor.
Verify the change #
To verify the hostname has been fully changed, enter the hostnamectl command:
Your new hostname will be printed on the terminal:
Conclusion #
We have shown you how to easily change the hostname on Ubuntu 20.04 installation without restarting the machine.
There are a number of reasons why you may need to change the hostname. The most common is when the hostname is automatically set upon the instance creation.
Feel free to leave a comment if you have any questions.