【Python】Python 2 测试网络连通性脚本

文章目录

    • 前言
    • [1. 命令行传参](#1. 命令行传参)
    • [2. 代码](#2. 代码)

前言

最近在只有python2的服务器上部署服务,不能用三方类库,这里出于好奇心学习下python。这里简单做个脚本,实现了检验网络连通性的功能(类似于curl)。

1. 命令行传参

使用命令行的目的是可以一次性检验多个url的连通性,比如上线前对接多个三方接口可以用上。

bash 复制代码
python test_socket.py -u "{'https://www.baidu.com':'120.232.145.144','ws://localhost:8080/ws':'127.0.0.1','wss://hello/ws':''}" 

参数解释

json 复制代码
{
	'https://www.baidu.com':'120.232.145.144', // 期待域名解析为120.232.145.144 否则报错
	'ws://localhost:8080/ws':'127.0.0.1',  // 期待域名解析为127.0.0.1 否则报错
	'wss://hello/ws':''  // 无期望域名解析的ip,保证连通性即可
}

2. 代码

python 复制代码
# -*- coding: utf-8 -*-

# coding:utf-8
import sys
import getopt
import socket
import urlparse
import re


def get_hostname(input_url):
    if len(input_url) == 0:
        return 'url为空'
    hostname = urlparse.urlparse(input_url).hostname
    if hostname is None:
        return '域名解析为空'
    try:
        return socket.gethostbyname(hostname)
    except socket.error:
        return '域名解析异常'


def get_port(input_url):
    if len(input_url) == 0:
        return 'url为空'
    # url 上读端口号
    input_port = urlparse.urlparse(input_url).port
    if input_port:
        return input_port
    # url 上读不到端口号用协议类型区分
    scheme = urlparse.urlparse(input_url).scheme
    if scheme == 'https' or scheme == 'wss':
        return 443
    if scheme == 'http' or 'ws':
        return 80


def check_connect(input_ip, input_port):
    # 设置超时时间为3秒钟
    socket.setdefaulttimeout(3)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((input_ip, input_port))
        return '可联通'
    except socket.timeout:
        return '无法联通, 超时'
    except Exception as e:
        return '无法联通, 异常:' + str(e)
    finally:
        s.close()


# 从命令行中读取参数
opts, argv = getopt.getopt(sys.argv[1:], 'u:')
ops = dict(opts)
url_ip_dict = eval(ops.get('-u'))

# 循环参数内容进行连通性检测
print "-"*150
printTemplate = "%-60s %-20s %-20s %-50s"
print printTemplate % ('url', 'ip', 'port', 'result')
print "-"*150
for input_url, input_ip in url_ip_dict.iteritems():
    # 域名解析
    actual_ip = get_hostname(input_url)
    # 未能解析出ip为异常
    if not re.match(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', input_ip):
        print printTemplate % (input_url, '\\', '\\', actual_ip)
        continue

    # 解析出ip, 且入参存在ip 则校验是否是解析出来的ip
    if input_ip:
        if actual_ip != input_ip:
            print printTemplate % (input_url, input_ip, '\\', '未能联通, 实际解析的ip为' + actual_ip)
            continue

    port = get_port(input_url)
    # 连通性测试
    result = check_connect(actual_ip, port)
    print printTemplate % (input_url, actual_ip, port, result)
相关推荐
DevSecOps选型指南39 分钟前
2025软件供应链安全最佳实践︱证券DevSecOps下供应链与开源治理实践
网络·安全·web安全·开源·代码审计·软件供应链安全
lyaihao1 小时前
使用python实现奔跑的线条效果
python·绘图
ai大师1 小时前
(附代码及图示)Multi-Query 多查询策略详解
python·langchain·中转api·apikey·中转apikey·免费apikey·claude4
国科安芯2 小时前
抗辐照MCU在卫星载荷电机控制器中的实践探索
网络·嵌入式硬件·硬件工程·智能硬件·空间计算
小小爬虾2 小时前
关于datetime获取时间的问题
python
EasyDSS3 小时前
国标GB28181设备管理软件EasyGBS远程视频监控方案助力高效安全运营
网络·人工智能
玩转4G物联网3 小时前
零基础玩转物联网-串口转以太网模块如何快速实现与TCP服务器通信
服务器·网络·物联网·网络协议·tcp/ip·http·fs100p
蓝婷儿3 小时前
6个月Python学习计划 Day 16 - 面向对象编程(OOP)基础
开发语言·python·学习
派阿喵搞电子3 小时前
Ubuntu下有关UDP网络通信的指令
linux·服务器·网络
chao_7893 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表