Python实现的tcp端口检测操作示例

yipeiwu_com5年前Python基础

本文实例讲述了Python实现的tcp端口检测操作。分享给大家供大家参考,具体如下:

# coding=utf-8
import sys
import socket
import re
def check_server(address, port):
  s = socket.socket()
  print 'Attempting to connect to %s on port %s' % (address, port)
  try:
    s.connect((address, port))
    print 'Connected to %s on port %s' % (address, port)
    return True
  except socket.error as e:
    print 'Connection to %s on port %s failed: %s' % (address, port, e)
    return False
if __name__ == '__main__':
  from argparse import ArgumentParser
  parser = ArgumentParser(description=u'TCP端口检测')
  parser.add_argument(
    '-a',
    '--address',
    dest='address',
    default='localhost',
    help='address for the server')
  parser.add_argument(
    '-p',
    '--port',
    dest="port",
    default=80,
    type=int,
    help='port for the server')
  args = parser.parse_args()
  check = check_server(args.address, args.port)
  print 'check_server returned %s' % check
  sys.exit(not check)

测试结果:

[hupeng@hupeng-vm Python]$python check_server.py && echo "SUCCESS"
Attempting to connect to localhost on port 80
Connected to localhost on port 80
check_server returned True
SUCCESS
[hupeng@hupeng-vm Python]$python check_server.py -p 81 && echo "Failure"
Attempting to connect to localhost on port 81
Connection to localhost on port 81 failed: [Errno 111] Connection refused
check_server returned False
[hupeng@hupeng-vm Python]$python check_server.py -p 81 || echo "Failure"
Attempting to connect to localhost on port 81
Connection to localhost on port 81 failed: [Errno 111] Connection refused
check_server returned False
Failure

附:

shell中&&||的使用方法

命令的返回结果:真(返回0),假(返回非0)

command1  && command2: command1返回真时,command2才会被执行

command1  || command2:command1返回真时,command2就不会被执行

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python系统监控模块psutil功能与经典用法分析

本文实例讲述了Python系统监控模块psutil功能与经典用法。分享给大家供大家参考,具体如下: 1.  psutil模块概述 psutil是一个跨平台库(http://co...

python PIL模块与随机生成中文验证码

python PIL模块与随机生成中文验证码

在这之前,你首先得了解Python中的PIL库。PIL是Python Imaging Library的简称,PIL是一个Python处理图片的库,提供了一系列模块和方法,比如:裁切,平移...

python在Windows8下获取本机ip地址的方法

本文实例讲述了python在Windows8下获取本机ip地址的方法。分享给大家供大家参考。具体实现方法如下: import socket hostname = socket.ge...

Python中创建字典的几种方法总结(推荐)

1、传统的文字表达式: >>> d={'name':'Allen','age':21,'gender':'male'} >>> d {'age':...

Python实现数据库并行读取和写入实例

Python实现数据库并行读取和写入实例

这篇主要记录一下如何实现对数据库的并行运算来节省代码运行时间。语言是Python,其他语言思路一样。 前言 一共23w条数据,是之前通过自然语言分析处理过的数据,附一张截图: 要实现...