The script shown below is my attempt at pinging multiple network namespaces using python 2.7 running on Linux (Fedora) OS.
Current status and problem:
When I run this file; the ping from elem1 (namespace) gets stored in a file called results.txt. But, I can't seem to get the loop to come back around and ping elem2, elem3, ... elemN
Attempted Fixes:
I tried killing the process using "kill -9 p.pid" (as shown) in the hope that this would kill the process and then a new process could be created on next iteration of the loop. However this is not the case! I've checked the documentation ( https://docs.python.org/2/library/subprocess.html ) and tried several different permutations of kill(), terminate(), removing shell=True etc... but to no avail.
import time
import os
import signal
import subprocess
IP_ADDR="192.168.1.1"
def main():
arry =["elem1", "elem2", "elem3", "elem4", "elem5", "elem6", "elem7"] array of network namespaces's to ping
with open('results.txt', 'a+') as outfile:
for elem in arry:
command = "ip netns exec {0} ping {1}".format(elem, IP_ADDR)
outfile.write("\n\nPinging {}\n".format(elem))
p = subprocess.Popen(command, shell=True, stdout=outfile)
command_kill = "kill -9 {}".format(p.pid)
time.sleep(2) #wait 5 seconds
p.kill()
outfile.close()
if __name__ == '__main__':
main()
My Questions:
(1) Can someone explain what the code is doing here?
(2) Can you suggest a means to achieve my aforementioned goal?
Thank you