So long story short my code is vulnerable as can be evidenced on Codacy, and I've been working hard to resolve the issue but I just cannot figure it out and at this stage I'm hoping someone with a little more know-how on the utilisation of subprocess.Popen can help me convert my old code to new code? Please.
I've been trying for days to swap what I currently have:
os.system(f"ping {pingreq_ip_entered} -c 3")
for something more secure, which when I've done some research seems to be using subprocess instead of os.system, so I've tried doing variations of the following:
subprocess.Popen(ping {pingreq_ip_entered} -c 3)
and also:
subprocess.Popen(f"ping {pingreq_ip_entered} -c 3")
Yet with zero luck on any variations I've tried, and I'm finding it a bit tough to wrap my head around how subprocess even works - the above two are just the main examples of what I've tried. I'm not entirely sure what I'm doing wrong here, and the full code can be found at https://github.com/LostShepherdUK/Shepherd-Project, if anyone is willing to take a look over what I want to achieve and offer a response that isn't just 'copy-paste this it'll work' but actually talk me through a bit of where I've gone wrong while also providing an answer that'd be lovely as I want to take this as a learning opportunity not just a chance to rip someone's code and call it a day!
Thank you.
Answered by Kevin Crouse
CodePudding user response:
Safe subprocess should be called in list context. Also, presuming you want the output, you probably want something like this. capture_output saves standard output to stdout
and standard error to stderr
in bytes, so you need to decode them if you want text.
Also you can use returncode
instead of check_returncode()
if you want to handle your own errors.
import subprocess
cmdout = subprocess.run(["ping", pingreq_ip_entered, "-c", "3"], capture_output = True)
cmdout.check_returncode() # this throws an exception for you if the command failed.
ping_text = cmdout.stdout.decode("utf-8").strip().split("\n")
print(ping_info)