0

I am trying to ping a host using os.system('ping x.x.x.x -c 1') and I'm trying to make an if statement incase if the ping doesnt work, such as, if the host disables icmp requests or the host was not found. The structure of code im looking for is the following:

if pingcommand == not working:
       print("ICMP Not Working")
else:
   print("Working")

(P.S I am ONLY asking to use os.system() NOT subproccess) Operating System: Kali Linux (Recent) Python Version: 3.9

Xenoy
  • 67
  • 1
  • 8
  • 1
    `os.system` returns the exit code, not the output of the command, so check `!= 0` – OneCricketeer Dec 14 '20 at 17:36
  • Take a look at subprocess's [`.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run) or [`.Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen) methods. Collect the result into a variable and then compare it. – ti7 Dec 14 '20 at 17:36

1 Answers1

1

The os.system call returns an exit code that tells you if the application terminated correctly. Exit code 0 means correct termination. If an error occurs, you will get some other exit code, usually 1.

exit_code = os.system('ping 1.1.1.1 -c 1')

if exit_code == 0:
    print('Working')
else:
   print('Something went wrong')
sunnytown
  • 1,844
  • 1
  • 6
  • 13