Python Check Server Port Is Available (socket)

2022-10-14

筆記拋棄式的 Server Port 測試腳本,雖然 PowerShell 也很好處理這個問題,但這次就決定是你了 Python 君。

logo

說明

直接上程式碼,主要利用 socket 連線來確認伺服器的 Port,參考 bertcode 在 Gist 的範例程式。

import csv
import socket
import requests
import bs4

class Record:
    def __init__(self, record):
        self.name = record[0]
        self.ip = record[1]
        self.recordType = record[2]
        self.usage = record[3]

    def isOpen(self, port):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.settimeout(1)
            result = s.connect_ex((self.ip, int(port)))
            return result == 0
        except:
            return False

    def checkTitle(self, port):
      url = ''
      if port == 80:
        url = f'http://{self.name}' 
      if port == 443:
        url = f'https://{self.name}' 
      
      title = ''
      try:
        response = requests.get(url)
        title = bs4.BeautifulSoup(response.text).title.text
      except:
        pass
      return title.strip()

# CSV
"""
hostname, ip, recordType, usage
hostname1, 1.1.1.1, A, "DNS 1"
hostname2, 2.2.2.2, A, "AP 1"
hostname3, 3.3.3.3, A, "AP 2"
"""

recordLst = []

with open('.\data.csv', encoding='utf-8') as f:
    reader = csv.reader(f)

    for row in reader:
        recordLst.append(Record(row))

recordLst.pop(0) # pop out csv header

for row in recordLst:
    isHttp = row.isOpen(80)
    isHttps = row.isOpen(443)

    if isHttp:
      title = row.checkTitle(443)
    elif isHttp:
      title = row.checkTitle(80)
    else:
      title = ''
    print(f'{row.name} {"80" if isHttp else ""} {"443" if isHttps else ""} {title if title != "" else ""}')