python ping port code example

Example 1: python ping ip address

import os

ip_list = ['8.8.8.8']
for ip in ip_list:
    response = os.popen(f"ping {ip}").read()
    if "Received = 4" in response:
        print(f"UP {ip} Ping Successful")
    else:
        print(f"DOWN {ip} Ping Unsuccessful")

Example 2: check remote port is open or not using python

def port_check(HOST):
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   try:
      s.connect((HOST, int(22)))
      s.shutdown(2)
      return True
   except:
      return False