[英]Python Script to ping a list of specified hosts in a .txt file
我正在编写一个脚本,该脚本允许我 ping 多个主机以检查它们的状态。 目前我在运行以下我在网上找到的脚本时遇到了 2 个错误。 我更像是一名网络工程师而不是程序员。 我刚刚开始学习 python 但基础知识并不能帮助我解决这个问题。 在此先感谢您的帮助
回溯(最近一次通话最后):文件“/Users/p.petryszen/Documents/VsCode/Scripts/ping_hosts/ping_hosts.py”,第 45 行,待处理 = Queue.Queue() AttributeError: type object 'Queue' has no属性“队列”
回溯(最近一次通话最后):文件“/Users/p.petryszen/Documents/VsCode/Scripts/ping_hosts/ping_hosts.py”,第 45 行,待处理 = Queue.Queue() AttributeError: type object 'Queue' has no属性“队列”
import sys
import os
import platform
import subprocess
from queue import Queue
import threading
def worker_func(pingArgs, pending, done):
try:
while True:
# Get the next address to ping.
address = pending.get_nowait()
ping = subprocess.Popen(ping_args + [address],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
# Output the result to the 'done' queue.
done.put((out, error))
except Queue.Empty:
# No more addresses.
pass
finally:
# Tell the main thread that a worker is about to terminate.
done.put(None)
# The number of workers.
NUM_WORKERS = 4
plat = platform.system()
scriptDir = sys.path[0]
hosts = os.path.join(scriptDir, 'hosts.txt')
# The arguments for the 'ping', excluding the address.
if plat == "Windows":
pingArgs = ["ping", "-n", "1", "-l", "1", "-w", "100"]
elif plat == "Linux":
pingArgs = ["ping", "-c", "1", "-l", "1", "-s", "1", "-W", "1"]
else:
raise ValueError("Unknown platform")
# The queue of addresses to ping.
pending = Queue.Queue()
# The queue of results.
done = Queue.Queue()
# Create all the workers.
workers = []
for _ in range(NUM_WORKERS):
workers.append(threading.Thread(target=worker_func, args=(pingArgs, pending, done)))
# Put all the addresses into the 'pending' queue.
with open(hosts, "r") as hostsFile:
for line in hostsFile:
pending.put(line.strip())
# Start all the workers.
for w in workers:
w.daemon = True
w.start()
# Print out the results as they arrive.
numTerminated = 0
while numTerminated < NUM_WORKERS:
result = done.get()
if result is None:
# A worker is about to terminate.
numTerminated += 1
else:
print(result[0]) # out
print(result[1]) # error
# Wait for all the workers to terminate.
for w in workers:
w.join()
使用from queue import Queue
您只在脚本中导入了 object 队列,因此如果您想创建一个队列的新实例,您可以直接使用Queue()
,这意味着您将拥有:
from queue import Queue
# The queue of addresses to ping.
pending = Queue()
# The queue of results.
done = Queue()
如果您将模块队列作为一个整体导入,则需要指定 object 队列的来源
import queue
# The queue of addresses to ping.
pending = queue.Queue()
# The queue of results.
done = queue.Queue()
有关模块中的更多参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.