我们可以在一行中或全部打印来自“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/