Maison développement back-end Tutoriel Python 基于Python Shell获取hostname和fqdn释疑

基于Python Shell获取hostname和fqdn释疑

Jun 10, 2016 pm 03:06 PM

一直以来被Linux的hostname和fqdn(Fully Qualified Domain Name)困惑了好久,今天专门抽时间把它们的使用细节弄清了。

一、设置hostname/fqdn

在Linux系统内设置hostname很简单,如:

$ hostname florian

如果要设置fqdn的话,需要对/etc/hosts进行配置。

$ cat /etc/hosts
127.0.0.1 localhost
192.168.1.1 florian.test.com florian 
Copier après la connexion

/etc/hosts配置文件的格式是:

ip fqdn [alias]...

即第一列为主机ip地址,第二列为主机fqdn地址,第三列以后为别名,可以省略,否则至少要包含hostname。

上述配置文件的配置项的第一行为localhost的配置,第二行为主机名florian配置fqdn=florian.test.com,ip=192.168.1.1。
至于fqdn的域名后缀,最好和文件/etc/sysconfig/network的HOSTNAME配置保持一致:

$ cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=test.com
Copier après la connexion

二、查看hostname/fqdn

配置完成后,可以使用shell命令查看hostname和fqdn:

$ hostname && hostname -f 
florian
florian.test.com 
Copier après la connexion

使用ping去测试hostname的ip映射是否成功。

$ ping florian
PING florian.test.com (192.168.1.1) 56(84) bytes of data.
$ ping florian.test.com
PING florian.test.com (192.168.1.1) 56(84) bytes of data. 
Copier après la connexion

也可以使用python命令获取hostname和fqdn。

$ python 
Python 2.6.6 (r266:84292, Dec 7 2011, 20:48:22) 
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> socket.gethostname()
'florian'
>>> socket.getfqdn() 
'florian.test.com' 
Copier après la connexion

三、使用ip设置hostname带来的fqdn问题

以上描述了正常设置hostname和fqdn的方法,但是有时会使用ip地址直接作为hostname,此时会有些不同。

$ hostname 192.168.1.1
$ hostname && hostname -f
192.168.1.1
192.168.1.1 
Copier après la connexion

我们发现使用ip作为hostname后,使用shell命令查询hostname和fqdn都是ip地址!!!这是因为DNS协议会解析hostname的内容,当发现其为ip地址时,则不会再去查询/etc/hosts文件。

再使用python查看一下,会发现python获取的fqdn竟然还是florian.test.com!!!

$ python
Python 2.6.6 (r266:84292, Dec 7 2011, 20:48:22) 
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket 
>>> socket.gethostname()
'192.168.1.1'
>>> socket.getfqdn()
'florian.test.com' 
Copier après la connexion

即便是刷新dns缓存也无济于事:

$ service nscd reload

将/etc/hosts文件的第二行注释:

cat /etc/hosts
127.0.0.1 localhost
# 192.168.1.1 florian.test.com florian 
Copier après la connexion

刷新dns缓存:

$ service nscd reload

我们发现fqdn恢复正常了。

$ python
Python 2.6.6 (r266:84292, Dec 7 2011, 20:48:22) 
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket 
>>> socket.gethostname()
'192.168.1.1'
>>> socket.getfqdn()
'192.168.1.1' 
Copier après la connexion

之所以会有这样的行为,是因为python解析fqdn的逻辑和DNS并不完全一致,它会根据hostname查询对应的ip地址,然后在/etc/hosts内获取ip地址对应的配置行(第一行有效),然后解析fqdn列和alias列,并返回第一个包含字符'.'的对应列的值。

因此,使用ip设置hostname时,需要注意两点:

•首先,将hostname设置为ip地址
•其次,将/etc/hosts内包含该ip的配置项移除

为了保险起见,我们可以在/etc/hosts内尽可能靠前的位置添加如下配置:

cat /etc/hosts
127.0.0.1 localhost
192.168.1.1 192.168.1.1 
Copier après la connexion

这样,即便是之后有包含该ip的配置项也不会生效,python会优先解析第二行的配置项,并获取和ip地址完全一样的fqdn地址。当然,使用shell命令hostname获取fqdn也不会出错,因为hostname已经被设为ip地址形式了。

下面给大家介绍python shell 根据ip 获取 hostname || 根据hostname 获取 ip

利用 socket 模块 里的 gethostbyname 函数

<code class="hljs perl has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;">>>> import <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">socket</span> >>> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">socket</span>.<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">gethostbyname</span>(<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"www.baidu.com"</span>) <span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">'61.135.169.125'</span> >>> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">socket</span>.<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">gethostbyname</span>(<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"rs.xidian.edu.cn"</span>) <span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">'202.117.119.1'</span></code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li><li style="box-sizing: border-box; padding: 0px 5px;">4</li><li style="box-sizing: border-box; padding: 0px 5px;">5</li></ul>
Copier après la connexion

方法2 利用 shell 中 hostname 命令

<code class="hljs livecodeserver has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;">def getHostName(ip): <span class="hljs-command" style="box-sizing: border-box;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">command</span> = <span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">'java -jar %s %s "hostname > %s.hostname"'</span> %(<span class="hljs-title" style="box-sizing: border-box;">remoteCmdLoca</span>,<span class="hljs-title" style="box-sizing: border-box;">ip</span>,<span class="hljs-title" style="box-sizing: border-box;">ip</span>)</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">result</span> = subprocess.call(<span class="hljs-command" style="box-sizing: border-box;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">command</span>, <span class="hljs-title" style="box-sizing: border-box;">shell</span>=<span class="hljs-title" style="box-sizing: border-box;">True</span>)</span> <span class="hljs-command" style="box-sizing: border-box;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">command</span> = <span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">'%s -q -r -pw Sybase123 %s root@%s:/root'</span> % (<span class="hljs-title" style="box-sizing: border-box;">pscpLoca</span>, <span class="hljs-title" style="box-sizing: border-box;">pscpLoca</span>, <span class="hljs-title" style="box-sizing: border-box;">ip</span>)</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">result</span> = subprocess.call(<span class="hljs-command" style="box-sizing: border-box;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">command</span>, <span class="hljs-title" style="box-sizing: border-box;">shell</span>=<span class="hljs-title" style="box-sizing: border-box;">True</span>)</span> <span class="hljs-command" style="box-sizing: border-box;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">command</span> = <span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">'%s -q -r -pw Sybase123 root@%s:/root/%s.hostname %s'</span> %(<span class="hljs-title" style="box-sizing: border-box;">pscpLoca</span>,<span class="hljs-title" style="box-sizing: border-box;">ip</span>,<span class="hljs-title" style="box-sizing: border-box;">ip</span>,<span class="hljs-title" style="box-sizing: border-box;">sumAutoLoca</span>)</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">result</span> = subprocess.call(<span class="hljs-command" style="box-sizing: border-box;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">command</span>, <span class="hljs-title" style="box-sizing: border-box;">shell</span>=<span class="hljs-title" style="box-sizing: border-box;">True</span>)</span> fileName = sumAutoLoca + ip + <span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">'.hostname'</span> readFile = <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">open</span>(fileName,<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">'r'</span>) hostnameInfo = str(readFile.readline().strip(<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">'\n'</span>)) readFile.<span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">close</span>() subprocess.call(<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">'rm '</span>+ fileName, <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">shell</span>=True) print <span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"=========%s hostname is %s========"</span> %(ip,hostnameInfo) <span class="hljs-constant" style="box-sizing: border-box;">return</span> hostnameInfo</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li><li style="box-sizing: border-box; padding: 0px 5px;">4</li><li style="box-sizing: border-box; padding: 0px 5px;">5</li><li style="box-sizing: border-box; padding: 0px 5px;">6</li><li style="box-sizing: border-box; padding: 0px 5px;">7</li><li style="box-sizing: border-box; padding: 0px 5px;">8</li><li style="box-sizing: border-box; padding: 0px 5px;">9</li><li style="box-sizing: border-box; padding: 0px 5px;">10</li><li style="box-sizing: border-box; padding: 0px 5px;">11</li><li style="box-sizing: border-box; padding: 0px 5px;">12</li><li style="box-sizing: border-box; padding: 0px 5px;">13</li><li style="box-sizing: border-box; padding: 0px 5px;">14</li></ul>
Copier après la connexion

设计思路 ##

有时候socket不太稳定, 具体原因带查明

目的: 根据 ip 获取 hostname (适当改进也可逆转)

先设计了一个远程执行 ssh 命令jar, 或者可以用plink, 链接enter link description here

利用subprocess.call命令在远程ip机器上执行hostname > %s.hostname命令, 将hostname 信息输出到文件

用pscp将本地的pscp文件复制到远程ip机器上 /root 目录下(后来发现这步不需要)

然后利用本地的 pscp 将远程机器上带有hostname的文本文件/root/%s.hostname 复制到本地

利用 python 的文本读取功能读取信息, 从中取出hostname字符串

再利用 rm 命令把远程机器和本地的文本文件都删除

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment résoudre le problème des autorisations rencontré lors de la visualisation de la version Python dans le terminal Linux? Comment résoudre le problème des autorisations rencontré lors de la visualisation de la version Python dans le terminal Linux? Apr 01, 2025 pm 05:09 PM

Solution aux problèmes d'autorisation Lors de la visualisation de la version Python dans Linux Terminal Lorsque vous essayez d'afficher la version Python dans Linux Terminal, entrez Python ...

Comment utiliser la belle soupe pour analyser HTML? Comment utiliser la belle soupe pour analyser HTML? Mar 10, 2025 pm 06:54 PM

Cet article explique comment utiliser la belle soupe, une bibliothèque Python, pour analyser HTML. Il détaille des méthodes courantes comme find (), find_all (), select () et get_text () pour l'extraction des données, la gestion de diverses structures et erreurs HTML et alternatives (Sel

Comment effectuer l'apprentissage en profondeur avec TensorFlow ou Pytorch? Comment effectuer l'apprentissage en profondeur avec TensorFlow ou Pytorch? Mar 10, 2025 pm 06:52 PM

Cet article compare TensorFlow et Pytorch pour l'apprentissage en profondeur. Il détaille les étapes impliquées: préparation des données, construction de modèles, formation, évaluation et déploiement. Différences clés entre les cadres, en particulier en ce qui concerne le raisin informatique

Comment copier efficacement la colonne entière d'une dataframe dans une autre dataframe avec différentes structures dans Python? Comment copier efficacement la colonne entière d'une dataframe dans une autre dataframe avec différentes structures dans Python? Apr 01, 2025 pm 11:15 PM

Lorsque vous utilisez la bibliothèque Pandas de Python, comment copier des colonnes entières entre deux frames de données avec différentes structures est un problème courant. Supposons que nous ayons deux dats ...

Comment créer des interfaces de ligne de commande (CLI) avec Python? Comment créer des interfaces de ligne de commande (CLI) avec Python? Mar 10, 2025 pm 06:48 PM

Cet article guide les développeurs Python sur la construction d'interfaces de ligne de commande (CLI). Il détaille à l'aide de bibliothèques comme Typer, Click et Argparse, mettant l'accent sur la gestion des entrées / sorties et promouvant des modèles de conception conviviaux pour une meilleure convivialité par la CLI.

Quelles sont les bibliothèques Python populaires et leurs utilisations? Quelles sont les bibliothèques Python populaires et leurs utilisations? Mar 21, 2025 pm 06:46 PM

L'article traite des bibliothèques Python populaires comme Numpy, Pandas, Matplotlib, Scikit-Learn, Tensorflow, Django, Flask et Demandes, détaillant leurs utilisations dans le calcul scientifique, l'analyse des données, la visualisation, l'apprentissage automatique, le développement Web et H et H

Expliquez le but des environnements virtuels dans Python. Expliquez le but des environnements virtuels dans Python. Mar 19, 2025 pm 02:27 PM

L'article traite du rôle des environnements virtuels dans Python, en se concentrant sur la gestion des dépendances du projet et l'évitement des conflits. Il détaille leur création, leur activation et leurs avantages pour améliorer la gestion de projet et réduire les problèmes de dépendance.

Que sont les expressions régulières? Que sont les expressions régulières? Mar 20, 2025 pm 06:25 PM

Les expressions régulières sont des outils puissants pour la correspondance des motifs et la manipulation du texte dans la programmation, améliorant l'efficacité du traitement de texte sur diverses applications.

See all articles