Переименовать имя сервера 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)

Читайте также:  Linux boot windows partition in

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.

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.

Источник

Как изменить 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 , указав ей новое значение имени хоста:

Читайте также:  Opensuse linux настройка сети

Источник

Вики IT-KB

Здесь представлено несколько вариантов действий для смены имени хоста в операционной системе Debian GNU/Linux

Выяснить текущее имя хоста можно командой:

Смена имени с помощью утилиты hostname

Изменяем имя хоста с помощью команды hostname:

Смена имени с помощью утилиты sysctl

Кроме того, можно изменить имя хоста с помощью утилиты sysctl. Получить текущее имя хоста с помощью sysctl можно так:

Установить новое значение можно так:

# sysctl kernel.hostname=NEW-NAME

Конфигурационный файл hostname

Установка имени таким образом будет действовать до перезагрузки. В процессе загрузки имя хоста считывается из файла /etc/hostname/ . Изменим запись о хосте в этом файле:

После этого можно выполнить команду (она выполняется в процессе загрузки системы и считывает данные с файла /etc/hostname )

Конфигурационный файл hosts

Дополнительно нужно изменить запись о хосте в файле /etc/hosts :

127.0.0.1 localhost 10.1.0.2 NEW-NAME.holding.com NEW-NAME # The following lines are desirable for IPv6 capable hosts ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters

Проверено на следующих конфигурациях:

Автор первичной редакции:
Алексей Максимов
Время публикации: 06.12.2016 16:00

Обсуждение

Сжато, понятно и по делу! На таких авторах держится весь интернет. Большое спасибо за все твои публикации и эту тоже.

Алексей Максимов , 03.12.2020 21:35 , 03.12.2020 21:36

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

unix-linux/debian/change-hostname-on-debian-linux.txt · Последнее изменение: 25.11.2017 12:04 — Алексей Максимов

Источник

How do I change the hostname without a restart?

I want to change the OS hostname but I do not want to restart. I have edited /etc/hostname but it requires a restart to get implemented. How to avoid this?

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

14 Answers 14

It’s easy. Just click the Gear icon (located at upper right corner of the screen), open «About this computer» screen (located at Gear icon ) and edit «Device name».

Or, in a terminal, use the following command:

sudo hostname your-new-name 

This will set the hostname to your-new-name until you restart. See man hostname and How do I change the computer name? for further information. Do not use _ in your name.

After a restart your changes in /etc/hostname will be used, so (as you said in the question), you should still use

(or some other editor) so that file contains the hostname.

To test that the file is set up correctly, run:

sudo service hostname start 

You should also edit /etc/hosts and change the line which reads:

so that it now contains your new hostname. (This is required otherwise many commands will cease functioning.)

I know. that’s why you should use the ‘hostname’ command. I just wanted to clarify, that the ‘hostname’ command does only change the hostname until you restart/crash/etc. Afterwards it will read the name from the file again.

Читайте также:  Файлы windows под linux

Depends. If you entered the command you do not need to restart. The hostname is changed already. But only UNTIL your next restart.

In short, although hostname will cause the new name to take immediate effect, it is not «permanent» unless you also change /etc/hostname and /etc/hosts , since those are the files that will be read after a restart or a crash, which of course, you may not be expecting ahead of time.

Ubuntu 13.04 onwards

The hostnamectl command is part of the default installation on both Desktop and Server editions.

It combines setting the hostname via the hostname command and editing /etc/hostname . As well as setting the static hostname, it can set the «pretty» hostname, which is not used in Ubuntu. Unfortunately, editing /etc/hosts still has to be done separately.

hostnamectl set-hostname new-hostname 

This command is part of the systemd-services package (which, as of Ubuntu 14.04, also includes the timedatectl and localectl commands). As Ubuntu migrates to systemd , this tool is the future.

Note this isn’t available everywhere. Just looked on my Ubuntu 14.04 LTS ARM-7 installation, and hostnamectl doesn’t exist. Guess some flavours of Ubuntu aren’t using systemd yet.

@Stéphane the commands are part of the systemd suite, but they are available independently. In this case, 13.04-14.10 don’t use systemd as init, by the command is available.

@H2ONaCl the shell variable is set on startup, just open another shell and the hostname variable should be fine. As for sudo, the error about hostname resolution has never actually prevented me from doing anything.

@H2ONaCl ah, but the HOSTNAME variablle isn’t standard — IIRC dash and ksh don’t have it, zsh uses HOST, so as far as shell variables go, it’s the bottom of the heap.

Without Restart

Changing the hostname or computer name in ubuntu without restart

Edit /etc/hostname and change to the new value,

Edit /etc/hosts and change the old 127.0.1.1 line to your new hostname

127.0.0.1 localhost 127.0.1.1 ubuntu.local ubuntu # change to your new hostname/fqdn 

Note : i have read it on a forum > Edit /etc/hosts and change the old 127.0.1.1 line to your new hostname (if you don’t do this, you wont be able to use sudo anymore. If you have already done it, press ESC on the grub menu, choose recovery, and edit your host file to the correct settings)

Now after a reboot, your hostname will be the new one you chose

Without Reboot

To change without a reboot, you can just use hostname.sh after you edit /etc/hostname . You must keep both your host names in /etc/hosts (127.0.0.1 newhost oldhost) until you execute the command below:

sudo service hostname start 

Note : Above command to make the change active. The hostname saved in this file ( /etc/hostname ) will be preserved on system reboot (and will be set using the same service).

Источник

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