Reputation: 177
I am currently using python 2.7 and will need to ping windows and linux.
I want to create a function that will return the IP address from a ping within a python script. I currently have this function
def ping(host):
"""
Returns True if host responds to a ping request
"""
import subprocess, platform
# Ping parameters as function of OS
ping_str = "-n 1" if platform.system().lower()=="windows" else "-c 1"
args = "ping " + " " + ping_str + " " + host
need_sh = False if platform.system().lower()=="windows" else True
# Ping
return subprocess.call(args, shell=need_sh) == 0
Right now it just returns true or false but is there a way I can run ping(google.com) and have it return 216.58.217.206. I have a list of servers and IPs and I need to make sure that the IP addresses match the FQDN.
Upvotes: 0
Views: 5134
Reputation: 301
You can use the socket to get the IP of the host.
import socket
print(socket.gethostbyname('www.example.com'))
Upvotes: 4
Reputation: 41
Not sure how no-one has tried this method yet (for windows anyways)!
Use a WMI query of W32_PingStatus
With this method we return an object full of goodies
import wmi
# new WMI object
c = wmi.WMI()
# here is where the ping actually is triggered
x = c.Win32_PingStatus(Address='google.com')
# how big is this thing? - 1 element
print 'length x: ' ,len(x)
#lets look at the object 'WMI Object:\n'
print x
#print out the whole returned object
# only x[0] element has values in it
print '\nPrint Whole Object - can directly reference the field names:\n'
for i in x:
print i
#just a single field in the object - Method 1
print 'Method 1 ( i is actually x[0] ) :'
for i in x:
print 'Response:\t', i.ResponseTime, 'ms'
print 'TTL:\t', i.TimeToLive
#or better yet directly access the field you want
print '\npinged ', x[0].ProtocolAddress, ' and got reply in ', x[0].ResponseTime, 'ms'
Screenshot of output:
Upvotes: 0