I have hit another "wall"... I have the following script, which appears to work fine on Windows, however when I move it to Linux it seems to lose functionality.
Note: I added the print line(s) statements for troubleshooting.
The following script outputs the contents of the hostsFile when I print lines, and then prints each line in turn when I print line. But when it reaches the ping execution, it appears to jump straight to the last host in the file. I was wondering if I have missed something clearly obvious (I am still learning python as a newbie).
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()
Any thoughts/help is appreciated.
Many thanks in advance.
Regards,
MHibbin
EDIT: Thanks to Wooble for the help... the correct code should be (notice the spacing):
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()
communicateoutside the for loop, so you should expect it to only communicate once. This is not the code you're running on Windows if you're not seeing the same behavior.pingis in the path, or give the full path to it, and that the user executing the script has rights to executeping.