使用 Python 和 PyCharm IDE Ping 多台服务器

Pinging Multiple servers using Python with PyCharm IDE

我尝试使用主机名 ping 多台服务器,没有额外的 .txt 文件。 我正在尝试这样..

import os
for i in range(1,2): #`for i in range(1,2):
   hostname1= "google.con"  # example
   hostname2 = "google.com"  # example
response = os.system("ping -n 1 " + hostname1)
response = os.system("ping -n 1 " + hostname2)

然后检查响应...

if response == 0:
    flag = 'OK'
else:
    flag = 'KO'
if flag == 'OK':
    print('all hosts are up!')
else:
    print('something is wrong')

我是 Python 和 PyCharm 的新手。

NKalyan

你的代码毫无意义。尤其是你的 for-loop

您应该将主机保留在列表中并使用 for-loop 分别处理每个主机。

您不能多次分配 response,因为它会删除以前的值,您将只检查最后的结果。

import os

# --- before loop ---    

hostnames = ["google.con", "google.com", "whosebug.com"]

all_ok = True  # at start I assume that all hosts are OK

# --- loop ---

for host in hostnames:
    response = os.system("ping -n 1 " + host)
    if response != 0:
        all_ok = False  # one of host is down
    # don't use `else: all_ok = True` 

# --- after loop ---

if all_ok:
    print('all hosts are up!')
else:
    print('something is wrong')

您可以用类似的方式计算有问题的主机

import os

# --- before loop ---

hostnames = ["google.con", "google.com", "whosebug.com"]

count = 0

# --- loop ---

for host in hostnames:
    response = os.system("ping -n 1 " + host)
    if response != 0:
        count += 1  # one of host is down

# --- after loop ---

if count == 0:
    print('all hosts are up!')
else:
    print('number of down hosts:', count)

或者您可以使用有问题主机的列表

import os

# --- before loop ---

hostnames = ["google.con", "google.com", "whosebug.com"]

problems = []  # hosts with problems

# --- loop ---

for host in hostnames:
    response = os.system("ping -n 1 " + host)
    if response != 0:
        problems.append(host)  # one of host is down

# --- after loop ---

if not problems:  # if len(problems) == 0:
    print('all hosts are up!')
else:
    print('number of downed hosts:', len(problems))
    print('hosts:', problems)