Ping_Python 下面是ping主机的代码,并从结果中创建一个CSV文件。
import os
for i in range (0,255):
for j in range(1,254):
hostname = "10.222.{0}.{1}".format(i,j)
response = os.system ("ping -n 1 " + hostname)
if response == 0:
fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'w')
fp.writelines(hostname + "host up\n")
else:
fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'w')
fp.write(hostname + "host dead\n")
此代码允许我ping主机,但在将结果写入CSV时,它会覆盖以前写入的结果,只会写入倒数第二个或不完整的结果。
答案 0 :(得分:2)
更改
fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'w')
到
fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'a')
以便以追加模式打开文件。
您还可以使用with
改进代码,因此每次迭代都不会打开文件:
import os
with open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'a') as fp:
for i in range (0,255):
for j in range(1,254):
hostname = "10.222.{0}.{1}".format(i,j)
response = os.system ("ping -n 1 " + hostname)
if response == 0:
fp.writelines(hostname + "host up\n")
else:
fp.write(hostname + "host dead\n")
这也可以在脚本结束时关闭文件。