- Ubuntu Linux Change Hostname (computer name)
- Ubuntu change hostname command
- Display the current Ubuntu hostname
- How to change the Ubuntu server hostname without a system restart?
- Ubuntu Linux Change Hostname Using hostnamectl
- Conclusion
- Как изменить имя компьютера Ubuntu
- Требования к имени компьютера
- Как изменить имя компьютера
- Не меняется имя компьютера
- Выводы
- How to Change your Ubuntu Computer Name (Hostname)
- What is a computer name (hostname)?
- How to change the hostname?
- Method 1: Through the GUI
- Method 2: Manually through the hostname and hosts file
- Method 3: Through the hostnamectl command
- Conclusion
- Karim Buzdar
Ubuntu Linux Change Hostname (computer name)
I am a new Ubuntu Linux laptop user. I setup my computer name to ‘tom’ during installation but now I would like to change the computer name to ‘jerry’. Can you tell me how do I remove tom and set it to jerry on Ubuntu Linux? How do I change the Ubuntu computer name from ‘ubuntu’ to ‘AvlinStar’? Can you tell me more about Ubuntu Linux change hostname command?
You can use the hostname command or hostnamectl command to see or set the system’s host name. The host name or computer name is usually at system startup in /etc/hostname file. Open the terminal application and type the following commands to set or change hostname or computer name on Ubuntu Linux.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | Ubuntu Linux |
Est. reading time | 2 minutes |
Ubuntu change hostname command
The procedure to change the computer name on Ubuntu Linux:
- Type the following command to edit /etc/hostname using nano or vi text editor:
sudo nano /etc/hostname
Delete the old name and setup new name. - Next Edit the /etc/hosts file:
sudo nano /etc/hosts
Replace any occurrence of the existing computer name with your new one. - Reboot the system to changes take effect:
sudo reboot
Gif 01: Ubuntu change the computer name demo
Display the current Ubuntu hostname
Simply type the following command:
$ hostname
Sample outputs:
Fig.01: Ubuntu Linux Show the hostname/computer name command
How to change the Ubuntu server hostname without a system restart?
Type the following commands:
$ sudo hostname new-server-name-here
Next edit the /etc/hostname file and update hostname:
$ sudo nano /etc/hostname
Finally, edit the /etc/hosts file and update the lines that reads your old-host-name:
$ sudo nano /etc/hosts
From:
127.0.1.1 old-host-name
To:
127.0.1.1 new-server-name-here
Save and close the file.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Ubuntu Linux Change Hostname Using hostnamectl
Systemd based Linux distro such as Ubuntu Linux 16.04 LTS and above can simply use the hostnamectl command to change hostname. To see current setting just type the following command:
$ hostnamectl
Sample outputs:
To change hostname from nixcraft to viveks-laptop, enter:
$ hostnamectl set-hostname viveks-laptop
$ hostnamectl
Conclusion
In this tutorial, you learned how to change hostname on Ubuntu Linux. For more information see this page here.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Last file should be /etc/hosts instead of /etc/hostname
On any system using SystemD to check current:
hostnamectl
or:
hostname
To change:
hostnamectl set-hostname viveks-desktop
Very useful. I didn’t konw about changing /etc/hosts.
How about hostnamectl command?
Dear Vivek,
The above is good and solves to Change/Modify hostname/hosts..
But the same is not holds for System Name
Ex: vivek@ubuntu is changed as vivek@vivek_desktop or anything else..
But It could not change “vivek” to newname
Hi it worked and Thank you very much for your help
I have a Doubt about AWS EC2
i created a new instance using existing instance and i want to change the hostname of new instance automatically but it showing its private ip address only for the new one
please help me
my code is
aws ec2 create-tags –resources `aws ec2 run-instances –image-id –count 1 –instance-type t2.micro –key-name –user-data file://my-userdata.sh –subnet-id –security-group-ids |jq -r “.Instances[0].InstanceId”` –tags “Key=Name,Value=servername”
It’ll hold the value to the system, i mean persist the value even after restart if you add it to /etc/sysconfig/network
HOSTNAME=
Источник
Как изменить имя компьютера Ubuntu
Имя компьютера или по-другому, имя хоста устанавливается во время установки системы. Оно используется для идентификации компьютера в локальной сети, например, передается службой NetBIOS как имя сервера Samba, а также вы будете постоянно видеть его в терминале перед приглашением ввода команды.
Если вы задали не такое имя как хотите во время установки, то изменить имя компьютера Ubuntu не так уж сложно, но графических инструментов для этого в системе придумано не было, поэтому придется делать все через терминал.
Требования к имени компьютера
Вы можете использовать практически любое имя компьютера, но для него есть некоторые ограничения. Не желательно использовать два одинаковых имени компьютера в одной локальной сети, иначе могут возникнуть проблемы с различными интернет-сервисами и самая очевидная — вы не сможете понять где какой компьютер.
Второе ограничение — имя компьютера может содержать только буквы английского алфавита от a до z, цифры от 0 до 9, а также символы дефиса и точки. Начинаться и заканчиваться имя должно только буквой или цифрой, а не символом подчеркивания. Имя хоста регистронезависимо, поэтому COMPUTER и computer будут означать одно и то же. По длине стоит ограничение от 2 до 69 символов, но этого вполне достаточно.
Как изменить имя компьютера
Посмотреть текущее имя компьютера можно выполнив команду hostnamectl без параметров:
Изменить имя хоста Ubuntu можно несколькими способами. Самый простой способ установить имя компьютера, которое сохранится только до перезагрузки можно использовать команду hostname, которой в параметре нужно передать новое имя. Например:
sudo hostname losst-pc
Но после перезагрузки все вернется как было раньше. Чтобы сделать изменения постоянными нужно изменить содержимое двух файлов. /etc/hostname и /etc/hosts:
sudo vi /etc/hostname
Удалите старое имя из этого файла и пропишите новое. Затем сохраните изменения.
В современных версиях Ubuntu вы можете использовать команду hostnamectl, в отличие от первого варианта изменения сохранятся после перезагрузки:
sudo hostnamectl set-hostname новое_имя
Затем откройте второй файл:
sudo vi /etc/hosts
Здесь немного сложнее, найдите строку:
И замените старое имя на новое, после этого необходимо перезагрузить компьютер. Если вы не хотите перезагружать систему, то вы можете просто перезагрузить сервис управления входом пользователей:
systemctl restart systemd-logind.service
Теперь все должно работать правильно. Но это не единственный способ сменить имя хоста в Ubuntu.
Не меняется имя компьютера
Если вы поменяли имя компьютера, а после перезагрузки восстанавливается все как было, например, какое-то там dhcpcd0-pc, то, скорее всего, виноват NetworkManager. Здесь решение либо удалить эту программу, либо изменить имя хоста Ubuntu с помощью NetworkManager. Для этого выполните:
sudo vi /etc/NetworkManager/NetworkManager.conf
И добавьте в файл такие строки:
Теперь после перезагрузки NetworkManager поменяет имя хоста Ubuntu на правильное и больше проблем с этим не будет.
Выводы
Вот и все, теперь вы знаете как сменить имя компьютера Ubuntu. Для этого есть вполне достаточно способов, чтобы вы могли выбрать именно то, что нужно. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
How to Change your Ubuntu Computer Name (Hostname)
What is a computer name (hostname)?
Your computer name, in technical terms, is also referred to as the hostname of your computer system. A hostname is how other computers recognize your computer over a local network. Like on the Internet, we have URLs instead of hostnames. These URLs contain regular words like google.com that we can easily understand instead of remembering the numeric IP address of a server.
We can give easy computer name/hostname for our systems so that other computers can easily identify it over a local network. So instead of remembering your IP address, other people can access local web pages and other authorized data on your system through your hostname.
In this article, we will give a few simple ways to change your computer name through the graphical user interface and the command line.
The commands and procedures mentioned in this article have been run on a Ubuntu 18.04 LTS system.
How to change the hostname?
Method 1: Through the GUI
Through the UI, you can change your computer’s device name. It can be called a “pretty hostname” as it is not the permanent or static hostname of your computer. Nevertheless, you can change the device name as follows:
Open your system settings either by clicking the downward arrow located at the top-right corner of your Ubuntu screen and then clicking the settings icon from the following view:
Open the Settings utility through the system Dash as follows:
The Settings utility will by default open in the Wi-Fi view as follows:
Move to the Details view by clicking the Details tab from the left pane. You will be able to view the Device name in the About view as follows: Advertisement
The device name will change as soon as you enter a new name in the Device name textbox.
Please note that this is not your computer’s permanent hostname. Please read further in this article to view how you can change your computer’s permanent hostname.
Method 2: Manually through the hostname and hosts file
You can view the hostname of your computer by entering the following command in your Terminal:
(Click the Ctrl+Alt+T shortcut to open the Terminal application)
One way to change the hostname is through the following command:
$ sudo hostname new-hostname
The drawbackof this method is that the hostname will revert to the original when you restart your system.
The proper way to change the hostname is by changing it in two configuration files named the hostname and hosts file located in the /etc/ folder.
You can open these files through any of your favorite text editors. We are opening this file in the nano editor as follows:
The only text in this file lists the hostname of your computer. Simply change the text to a new hostname and then exit and save the file by clicking Ctrl+X, and then y and hit enter.
Then open the hosts file as follows:
In this file, the hostname is listed against the IP: 127.0.1.1
Change this hostname to a new hostname and then exit and save the file by clicking Ctrl+X, and then y and hit enter.
Now when you restart the system, your hostname will change to a static new hostname.
Method 3: Through the hostnamectl command
The smartest way to change your hostname is through the hostnamectl command that is a part of the Systemd utility. If Systemd is not already installed on your system, you can install it through the following command as root:
You can check the version number of the Systemd utility by running the following command:
This command will give you the version number of the utility and also ensure that it is indeed installed on your system
Now that the Systemd utility is installed on your system, you can run the following command in order to view detailed information about your system, including the hostname:
In this output, the Static hostname lists the permanent hostname of your machine. The Pretty hostname lists the Device name you have set up through the UI in the Settings utility. The hostnamectl lists the Pretty hostname(device name) only if it is different from the static hostname.
In order to change your computer’s hostname through the hostnamectl command, use the following syntax:
$ hostnamectl set-hostname “new-hostname”
Now when you see, the hostname through the hostnamectl command, it will show the static hostname as the new hostname you have set. The system has also changed the device name to the hostname you specified through the set-hostname command.
You can verify through the UI that your device name will also be the same as your static hostname. Open the Settings utility and move to the Details tab to view your device name.
The plus point of the Hostnamectl command is that you do not need to restart your computer in order to permanently change the hostname.
Conclusion
Through this tutorial, you learned to change the device name and computer name(hostname) of your system. Now you can change your computer’s hostname either temporarily or permanently through the Ubuntu command line. All you need to do is change a few configuration files or simply use the hostnamectl command to do so. Now you can have a customized computer name through which other computers over the local area will identify you.
Karim Buzdar
About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn
Источник