简体   繁体   English

将文本文件中的 IP 转换为主机名

[英]Convert IP in text file to Hostname

I'm trying to get hostnames using IPs from text file, but I'm unable to read all IPs from text file and the output shows only one IP.我正在尝试使用文本文件中的 IP 获取主机名,但我无法从文本文件中读取所有 IP,并且输出仅显示一个 IP。

Below is my COde,下面是我的代码,

import os
import socket

with open('ips.txt', 'r') as f:
    for line in f.read().strip('\n'):
        ip = line.strip()
        b = socket.getfqdn(ip)
        print b

Thanks.谢谢。

The problem is in:问题在于:

for line in f.read().strip('\n'):

this iterates over the whole file content ( f.read() ) without the trailing \\n .这会遍历整个文件内容( f.read() ),而没有尾随\\n Strings are iterables in Python, so essentially you are just iterating over each character of the text file.字符串在 Python 中是可迭代的,因此本质上您只是迭代文本文件的每个字符。

Instead, as file objects are iterable, you can do the iteration line by line and get the relevant FQDN:相反,由于文件对象是可迭代的,您可以逐行进行迭代并获得相关的 FQDN:

with open('ips.txt', 'r') as f:
    for line in f:
        ip = line.strip()
        fqdn = socket.getfqdn(ip)
        # print(fqdn)  # Python 3
        print fqdn  # python 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python脚本中将IP地址从文本文件分配给主机名 - How do I assign IP address from text file to hostname in python script 需要帮助来创建一个Python脚本,该脚本从txt文件中读取主机名,对主机名执行ping操作,解析IP并将其打印到另一个文本文件 - Need help creating a Python script that reads hostnames from a txt file, pings the hostname, resolves the IP and prints it to another text file 无法获取主机名和 IP 并输出到文件 Python3 - Unable to get Hostname and IP and output to file Python3 如何在不写入主机文件的情况下将IP映射到python中的主机名 - How to Map an IP to hostname in python without writing in hosts file 通过Lamba功能创建EMR:在配置文件中获取主机名/ IP - Creating EMR via Lamba Function: Getting Hostname/IP in Config file 从 Python 中的文本文件中提取主机名和日期时间 - Extract hostname and datetime from text file in Python 用于 IP 捕获或主机名的正则表达式 - Regex for IP capture or hostname Python-IP到主机名脚本 - Python - IP to hostname script Python-将包含IP地址和不同数据的文本文件列表转换为CSV - Python - Convert a list from a text file containing IP's addresses and dissimilar data, to CSV Python中的快速主机名/ IP检查? - Fast hostname/IP check in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM