1

So I'm trying to ping a website such as Microsoft or Google and print out the results, but when I run the script it just says: "IP address must be specified.". I've tried looking around to see why this is happening, but can't seem to narrow down a solution.

Here's my code:

import subprocess

print('Ping www.microsoft.com')
print()
address = 'www.microsoft.com'
subprocess.call(['ping', '-c 3', address])

Am I doing something wrong? If so, any help or explanation would be greatly appreciated!

SpaceGrape
  • 35
  • 5
  • 3
    I'd try `subprocess.call(['ping', '-c', '3', address])` oh and perhaps try replacing `-c` with `-n` –  Mar 19 '19 at 03:32
  • Surely a question like this has been asked before https://stackoverflow.com/questions/2953462/pinging-servers-in-python Perhaps use an existing library like https://github.com/romana/multi-ping or using the `scapy` library https://stackoverflow.com/questions/7541056/pinging-an-ip-range-with-scapy – Leonid Mar 19 '19 at 03:34
  • @JustinEzequiel Right on! Thank you, that worked with -n. I really appreciate it. – SpaceGrape Mar 19 '19 at 03:44
  • 1
    Possible duplicate of [Pinging servers in Python](https://stackoverflow.com/questions/2953462/pinging-servers-in-python) – tripleee Mar 19 '19 at 03:59
  • Possible duplicate of https://stackoverflow.com/questions/4256107/running-bash-commands-in-python – tripleee Mar 19 '19 at 03:59

1 Answers1

1

To show the output of the subprocess call you can use check_output method: See this answer for details

import subprocess

def ping():
  print('Ping www.microsoft.com')
  print()
  address = 'www.microsoft.com'
  print(subprocess.check_output(['ping', '-c', '3', address]).decode())

ping()

Output:

Ping www.microsoft.com

PING e13678.dspb.akamaiedge.net (23.53.160.151) 56(84) bytes of data.
64 bytes from a23-53-160-151.deploy.static.akamaitechnologies.com (23.53.160.151): icmp_seq=1 ttl=55 time=83.6 ms
64 bytes from a23-53-160-151.deploy.static.akamaitechnologies.com (23.53.160.151): icmp_seq=2 ttl=55 time=83.5 ms
64 bytes from a23-53-160-151.deploy.static.akamaitechnologies.com (23.53.160.151): icmp_seq=3 ttl=55 time=83.7 ms

--- e13678.dspb.akamaiedge.net ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 83.567/83.648/83.732/0.067 ms
arshovon
  • 13,270
  • 9
  • 51
  • 69