Hostname in linux file

Where does `hostname` store the hostname that I’ve set?

This is quite puzzling. Does anyone know where the hostname command stores and reads hostname from? I thought it was /etc/hostname but there is no such file on this Linux system that I’m using. I tried using strace to find where it was located but no read calls returned this information:

$ strace hostname 2>&1 | grep read read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\340^\0\0\0\0\0\0". 832) = 832 read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\340\30\2\0\0\0\0\0". 832) = 832 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\320\16\0\0\0\0\0\0". 832) = 832 read(3, "nodev\tsysfs\nnodev\trootfs\nnodev\tr". 1024) = 248 read(3, "", 1024) = 0 

5 Answers 5

Take a look at this related U&L Q&A titled: Where does uname get its information from?. Information such as the hostname persists within a data structure within the Linux kernel, while the system is running. During a system’s boot this information can be reattained through a variety of mechanisms that is typically distro specific.

If you look at the man 2 uname man page there’s a data structure mentioned there:

The 2nd element of that structure, nodename[] is one place where the hostname is stored within the Linux kernel.

/proc

If you take a look at /proc/sys/kernel/hostname , the hostname is exposed here as well. This is a virtual location, /proc , but it does give you an alternative method for accessing the hostname. The system’s domainname is here too, /proc/sys/kernel/domainname .

NOTE: Of interest, these values are UTS namespace specific.

Example

$ sudo hostname oldhost $ sudo unshare --uts /bin/bash $ sudo echo newhost > /proc/sys/kernel/hostname $ hostname newhost $ exit $ hostname oldhost 

Manipulating the hostname

On system’s with Systemd you can use the cli tool hostnamectl to get/set the hostname. This will change it permanently between reboots.

$ sudo hostnamectl set-hostname --static somehostname 

You can also find out it’s value through sysctl :

$ sudo sysctl -a | grep kernel.hostname kernel.hostname = myhostname 

For Fedora releases, this ask.fedoraproject.org Q&A covers the topic pretty thoroughly, titled: Correctly setting the hostname — Fedora 20 on Amazon EC2.

Meh. hostnamectl simply invokes a system call. How does the syscall store the information so that it’s persistent across reboots? That’s my question , if not the OPs as well.

The hostname command doesn’t store the name anywhere but kernel memory.

How the system decides what its name is at boot time depends on how the system is configured. Options range from reading a name from a file, to using DNS or /etc/hosts to set the name after a suitable network interface has been brought up.

Never /etc/hosts (which is for DNS lookups — a system that reads its hostname from there is oh so wrong) . but possibly /etc/hostname (contains the fully qualified name) or rarely /etc/sysconfig/network (may contain a HOSTNAME=. shell command). On an amazon EC2 instance you may also have to modifiy /etc/cloud/cloud.cfg .

Читайте также:  Linux найти все файлы новее

hostname(1) is just a front-end to the sethostname(3) system call, which basically writes the hostname to where the kernel expects it to be stored.

If you want the change to be permanent, as per general Unix philosophy you have to store it yourself. The precise location however depends heavily on your init system. For instance, OpenBSD’s init reads the hostname from /etc/myname (during netstart ).

All this should be described in your system’s manpages or supporting documentation.

As a long time *nix sysadmin, I’ll state the obvious, without a direct RTFM reference: 🙂

 hostnamectl may be used to query and change the system hostname and related settings. This tool distinguishes three different hostnames: the high-level "pretty" hostname which might include all kinds of special characters (e.g. "Lennart's Laptop"), the static hostname which is used to initialize the kernel hostname at boot (e.g. "lennarts-laptop"), and the transient hostname which is a fallback value received from network configuration. If a static hostname is set, and is valid (something other than localhost), then the transient hostname is not used. Note that the pretty hostname has little restrictions on the characters used, while the static and transient hostnames are limited to the usually accepted characters of Internet domain names. The static hostname is stored in /etc/hostname, see hostname(5) for more information. The pretty hostname, chassis type, and icon name are stored in /etc/machine-info, see machine-info(5). 

This holds true for most «linux» distros.

Источник

What is Hostname in Linux and How Can You Change It?

Linux Hostnames

When you visit a website, you type that website’s URL into your browser. That URL is made up of regular words that you can easily understand, like “maketecheasier.com.” Behind the scenes, a DNS server associates that name with a server’s IP address. This system exists because remembering IP addresses is awful, and no one would do it. Hostnames work the same way, only on a local network.

When you give your computer a hostname, it’s a regular word that you understand and can easily type in to identify that computer on your network. Just like a URL, you can substitute that hostname where you would regularly use an IP address. That includes browsing local web pages and using SSH. Unless you’re using a local DNS server, it takes a bit of setting up to make it run smoothly.

See Your Hostname

View Hostname Linux

Viewing your hostname is very easy. Open a terminal and run the hostname command. It’ll display your computer’s current hostname in the terminal window.

Setting Your Hostname

You probably set your computer’s hostname when you installed the operating system, but you can change it any time you choose. Historically, there have been several different ways to set a Linux computer’s hostname, but systemd has greatly simplified the process.

Читайте также:  Linux команды запуск kde

Systemd

On a computer running systemd, you can run the following command to change your computer’s hostname:

sudo hostnamectl set-hostname newname

Systemd will take care of resetting everything for you.

Old School Method

Hostname File Linux

The most universal traditional method involves modifying two files and restarting your computer. The first file is the “hostname” file. Surprising, right? It’s a plain test file with a single word in it. The system reads that word and sets it as the hostname, so put whatever you like there to make it the system’s hostname. It’s located at “/etc/hostname.”

Linux Hosts File

Next, there’s the “hosts” file. That file tells your system which hostnames to associate with IP addresses. You need to tell it to associate your hostname with the local computer. This one is located at “/etc/hosts;” open it once locate it.

There are two lines there that you need to concern yourself with, and it should look something like this:

127.0.0.1 localhost 127.0.1.1 hostname

Change only the second one that has your current hostname. When you’re done, save, exit, and reboot your computer.

Hosts File

The “hosts” file acts sort of like an ultra-simplified DNS server. It’s the file that lets your computer match up a hostname with an IP address on your network. You can find the file at “/etc/hosts.” Open it once you locate it.

The file is divided into two sections. The top handles the IPv4 addresses that you’re used to, and the bottom is IPv6. If you followed the traditional method, you set your own hostname at the top.

Linux Add Host To File

To add the hostnames of other devices on your network, create new lines below the two for your computer, and follow the same format. First, include the local IP of the device. Then, specify its hostname.

127.0.0.1 localhost 127.0.1.1 hostname 192.168.1.110 localserver

When you’re done, restart networking on your computer. It should be as simple as restarting the network service.

sudo systemctl restart networking

Now you’re able to access your new entry via its hostname. Try getting in with SSH.

If you were able to connect, everything is set up and working properly. You now have a solid handle on what hostnames are in Linux and how to make use of them to simplify access to your networked devices.

Nick is a freelance tech. journalist, Linux enthusiast, and a long time PC gamer.

Our latest tutorials delivered straight to your inbox

Источник

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

Как изменить Hostname

Hostname (имя компьютера, имя хоста) задается во время установки системы Linux. Hostname определяет название компьютера и используется преимущественно для идентификации компьютера в сети. Нельзя назначать два одинаковых Hostname для компьютеров в одной сети.

Просмотр текущего Hostname

Чтобы показать текущий Hostname можно использовать команду hostname без параметров:

Также Hostname можно отобразить командой hostnamectl :

Как изменить Hostname

Рассмотрим, как изменить Hostname двумя разными способами.

Способ 1. Используем команду hostnamectl

Во многих systemd-based дистрибутивах (например, в Ubuntu Linux) есть утилита hostnamectl .

Читайте также:  What is named service in linux

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

Источник

How to Set or Change System Hostname in Linux

Device or system hostnames are used to easily recognize a machine within a network in a human readable format. It is not much of a surprise, but on Linux system, the hostname can be easily changed by using simple command as “hostname“.

Running hostname on its own, without any parameters, will return the current hostname of your Linux system like this:

$ hostname TecMint 

If you want to change or set hostname of your Linux system, simply run:

Of course, you will need to replace “NEW_HOSTNAME” with the actual hostname that you wish to set. This will change the hostname of your system immediately, but there is one problem – the original hostname will be restored upon next reboot.

There is another way to change the hostname of your system – permanently. You might have already figured it out that this will require change in some configuration files and you will be correct.

Set System Hostname Permanently in Linux

Newer version of different Linux distributions such as latest Ubuntu, Debian, CentOS, Fedora, RedHat, etc. comes with systemd, a system and service manager that provides a hostnamectl command to manage hostnames in Linux.

To set system hostname on SystemD based distributions, we will use hostnamectl command as shown:

$ sudo hostnamectl set-hostname NEW_HOSTNAME

For Older Linux distributions, which uses SysVinit in short init, can have their hostnames changed by simply editing the hostname file located in:

You then have to add another record for the hostname in:

On RHEL/CentOS based systems that use init, the hostname is changed by modifying:

Here is a sample of that file:

/etc/sysconfig/network NETWORKING=yes HOSTNAME="tecmint.com" GATEWAY="192.168.0.1" GATEWAYDEV="eth0" FORWARD_IPV4="yes"

To keep a permanent hostname change the value next to «HOSTNAME» to the one of your hostname.

Conclusion

This simple article meant to show you a simple Linux trick and I hope that you learned something new.

Источник

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