19
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで、あるTCPポートに接続できるかを確認する

Last updated at Posted at 2015-05-10

あるホストが起動するまで待つとか、そういう用途につかったりします。

import sys
import socket
import time
import argparse

parser = argparse.ArgumentParser(description='Check tcp connectivity')
parser.add_argument('--host', dest='host', type=str, help='target host')
parser.add_argument('--port', dest='port', type=int, help='target port')
parser.add_argument('--interval', dest='interval', type=int, default='3', help='interval to check')
parser.add_argument('--retries', dest='retries', type=int, default='3', help='number of retries')
args = parser.parse_args()

def check_tcp_connectivity(host, port, interval=0, retries=1):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    for x in range(retries):
        try:
            s.connect((host, port))
            s.close()
            return True
        except socket.error as e:
            time.sleep(interval)

    s.close()
    return False

if check_tcp_connectivity(args.host, args.port, args.interval, args.retries):
    sys.exit(0)
else:
    sys.exit(1)

使う

python check.py --host 192.168.0.1 --port 22

参照

argparse
socket
time
sys

19
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?