简体   繁体   English

需要帮助来创建一个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

Just like the title says, I need to be pointed in the right direction on this. 就像标题所说的那样,我需要指出正确的方向。 I'm not looking for "Here's your code" (I recently began coding in Python, so my understanding is at very basic level) 我不是在寻找“这是您的代码”(我最近开始使用Python进行编码,因此我的理解是非常基础的)

But basically I will have a txt file full of hostnamnes (one on each row) that I need to ping to see if they are 1. Active and 2. What the IP-address of that active hostname is. 但基本上,我将拥有一个充满主机名的txt文件(每行一个),我需要对其进行ping操作以查看它们是否为1. Active和2。该活动主机名的IP地址是什么。 And then I need the program to output the hostname + IP to a txt file. 然后,我需要该程序将主机名+ IP输出到txt文件。

I read up a bit on the subject and it seems that subprocess is the way to go. 我阅读了一些有关该主题的内容,看来子过程是必经之路。 Time isn't really relevant so I don't need it to multi thread. 时间不是很重要,所以我不需要多线程。

So in conclusion, any good tips on where to begin (so that I may understand what I'm typing)? 因此,总而言之,有什么好的开始技巧(以便我可以理解自己在键入什么)吗?

EDIT:: So this is how far i have gotten: 编辑:: 所以这是我走了多远:

import ping, socket

hostsFile = open('hostnames.txt', 'r')
lines = hostsFile.readlines()
addr = socket.gethostbyname(lines)

for lines in hostsFile:
    print 'IP-address of', hostname
    print 'is', addr 
    try:
        ping.verbose_ping(count=3)
        delay = ping.Ping(timeout=2000).do()
    except socket.error, e:
        print "Ping Error:", e

It now returns an error referring to the addr = socket.gethostbyname(lines) line, saying: "TypeError: must be string, not list" 现在,它返回一个错误,该错误引用了addr = socket.gethostbyname(lines)行,并说:“ TypeError:必须为字符串,而不是列表”

While i do understand the error somewhat, i have no idea how to get around it. 虽然我确实了解该错误,但我不知道如何解决该错误。

You can use ping and socket modules of python to achieve the desired task. 您可以使用python的ping和socket模块来完成所需的任务。 Socket module has a function gethostbyname() which takes hostname and return its ip address. 套接字模块具有一个函数gethostbyname() ,该函数采用主机名并返回其ip地址。

The relevant code is shown below, You can implement the functionality of reading from and writing to the text file in this code. 相关代码如下所示,您可以在此代码中实现读取和写入文本文件的功能。

import ping, socket
hostname = 'maps.google.com'
addr = socket.gethostbyname(hostname)
print 'The address of ', hostname, 'is', addr
try:
    ping.verbose_ping('www.google.com', count=3)
    delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
except socket.error, e:
    print "Ping Error:", e

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM