0

I want to write a python script that should check if a particular IP address is reachable or not. I'm new to python programming and have no idea how the code might look. Help out

Goblin
  • 43
  • 2
  • 3
  • 8

2 Answers2

8

You can try like this;

>>> import os
>>> if os.system("ping -c 1 google.com") == 0:
...     print "host appears to be up"
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
6

You can use the subprocess module and shlex module to parse the shell command like below

import shlex
import subprocess

# Tokenize the shell command
# cmd will contain  ["ping","-c1","google.com"]     
cmd=shlex.split("ping -c1 google.com")
try:
   output = subprocess.check_output(cmd)
except subprocess.CalledProcessError,e:
   #Will print the command failed with its exit status
   print "The IP {0} is NotReacahble".format(cmd[-1])
else:
   print "The IP {0} is Reachable".format(cmd[-1])
Ram
  • 1,115
  • 8
  • 20
  • Can you please brief 'shlex' in this context? Also, can this be done without using 'shlex'? – Goblin Sep 15 '14 at 09:26
  • @Goblin The shlex.split() can be useful when determining the correct tokenization for args( for unix shell) , Yes it can be done without shlex in that case you have to tokenize your command like cmd=["ping","-c1","google.com"] as list and pass to subprocess.check_ouptut this work is done by shlex.split() for you. for shlex reference read this link https://docs.python.org/2/library/shlex.html – Ram Sep 15 '14 at 09:43
  • 1
    it is the case when `rc = subprocess.call()` could be used. No need to raise exception if it is expected. – jfs Sep 24 '15 at 20:56