python - 我们可以在Python中打印socket.getfqdn和socket.gethostbyname的输出吗

标签 python sockets

我们可以在一行中或全部打印来自“socket.gethostbyname”和“socket.getfqdn”的信息吗?我可以使用以下代码。只需添加此内容

#!/usr/bin/python
import sys
import socket
#Name = socket.gethostbyname(host.strip())
#IPD = socket.getfqdn(host.strip())

with open("/home/karn/host1.txt", 'rw') as f:
#     print socket.gethostbyname(host.rstrip())  socket.getfqdn(host.strip())
  for host in f:
     print socket.gethostbyname(host.rstrip())

预期的是:

Server_Name             IP_Address
------------------------------------
server2.example.com         192.10.1.1
server2.example.com         192.10.1.2

目前,当我运行它时,它只返回 IP 地址,因为我只能输入“socket.gethostbyname”,它会返回...

192.10.1.1
192.10.1.2
192.10.1.3

最佳答案

您可以使用string formatting并切片在一起,例如:

print("{0[0]}\t{0[2][0]}".format(socket.gethostbyname_ex(host.rstrip())))

将打印

server2.example.com   192.10.1.1
server2.example.com   192.10.1.2

关于python - 我们可以在Python中打印socket.getfqdn和socket.gethostbyname的输出吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37047558/

相关文章:

c# - 将非 C++ 子项目集成到 CMake 项目中

python - 在 Bash 中,修改文件中的列和行

python - 删除 pandas 中的前导 NaN

Java 如何使用 ObjectInputStream 进行读取

c# - SocketAsyncEventArgs - 如何检测正在进行的套接字操作并终止?

python - django 中的 "python manage.py migrate "到底做什么?

python - Python HTTP服务器和线程

python - 使用抽象命名空间 unix 套接字时连接被拒绝

java - 如何在Java套接字编程中解析index.html文件中包含的style.css的路径

c - 尝试重新绑定(bind)已关闭的监听套接字失败(EADDRINUSE)?