Python脚本探测TCP/UDP端口是否连通

Python脚本探测TCP/UDP端口是否连通

TCP

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
    探测TCP端口是否连通
    python tcp_test.py <host> <port>
    支持系统默认自带的python2.6运行.
"""
import socket
import sys


def test_tcp_port(host, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(2)
        s.connect((host, port))
        s.close()
        return True
    except:
        return False


if len(sys.argv) != 3:
    print("Usage: python tcp_test.py <host> <port>")
    sys.exit(1)

host = sys.argv[1]
port = int(sys.argv[2])

if test_tcp_port(host, port):
    print("TCP port %d on %s is open." % (port, host))
else:
    print("TCP port %d on %s is closed." % (port, host))

UDP

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
    探测UDP端口是否连通
    python tcp_test.py <host> <port>
    支持系统默认自带的python2.6运行.
"""
import socket
import sys


def test_udp_port(host, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(2)
        s.connect((host, port))
        data, addr = s.recvfrom(1024)
        s.close()
        return True
    except:
        return False


if len(sys.argv) != 3:
    print("Usage: python udp_test.py <host> <port>")
    sys.exit(1)

host = sys.argv[1]
port = int(sys.argv[2])

if test_udp_port(host, port):
    print("UDP port %d on %s is open." % (port, host))
else:
    print("UDP port %d on %s is closed." % (port, host))

示例:

[chenyh@kjchukoumq2gzcus ~]$ python udp_test.py 10.201.201.34 12201
UDP port 12201 on 10.201.201.34 is closed.

[chenyh@kjchukoumq2gzcus ~]$ python tcp_test.py 10.196.68.154 8443
TCP port 8443 on 10.196.68.154 is open.

代码参考

1.https://mp.weixin.qq.com/s/pUPOZtrzzkZ6g3PHd5F1KQ

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇