我碰到了另一面“墙”...我有以下脚本,它似乎在 Windows 上运行良好,但是当我将它移到 Linux 时,它似乎失去了功能。
注意:我添加了打印行语句以进行故障排除。
以下脚本在 I 时输出 hostsFile 的内容,print lines
然后在 I 时依次打印每一行print line
。但是当它执行 ping 时,它似乎直接跳转到文件中的最后一个主机。我想知道我是否遗漏了一些明显的东西(我还在学习 python 作为新手)。
import sys, os, platform, subprocess
plat = platform.system()
scriptDir = sys.path[0]
hosts = os.path.join(scriptDir,'hosts.txt')
hostsFile = open(hosts, "r")
lines = hostsFile.readlines()
print lines
if plat == "Windows":
for line in lines:
line = line.strip( )
ping = subprocess.Popen(
["ping", "-n", "1", "-l", "1", "-w", "100", line],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print out
print error
elif plat == "Linux":
for line in lines:
print line
line = line.strip()
ping = subprocess.Popen(
["ping", "-c", "1", "-s", "1", "-l", "1",line],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print out
print error
hostsFile.close()
任何想法/帮助表示赞赏。
提前谢谢了。
问候,
米宾
编辑:感谢 Wooble 的帮助......正确的代码应该是(注意间距):
import sys, os, platform, subprocess
plat = platform.system()
scriptDir = sys.path[0]
hosts = os.path.join(scriptDir,'hosts.txt')
hostsFile = open(hosts, "r")
lines = hostsFile.readlines()
if plat == "Windows":
for line in lines:
line = line.strip( )
ping = subprocess.Popen(
["ping", "-n", "1", "-l", "1", "-w", "100", line],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print out
print error
if plat == "Linux":
for line in lines:
line = line.strip()
ping = subprocess.Popen(
["ping", "-c", "1", line],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print out
print error
hostsFile.close()