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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

详解windows python3.7安装numpy问题的解决方法

详解windows python3.7安装numpy问题的解决方法

我的是win7的系统,去python官网下载python3.7安装 CMD  #打开命令窗口 pip install numpy #在cmd中输入 提示 需要c++14....

你眼中的Python大牛 应该都有这份书单

你眼中的Python大牛 应该都有这份书单

在最新一期的话题中,80%读者认为Python是最好的编程语言,知乎上类似的问题也很多,例如如何入门Python?如何3个月内入门Python?虽然现在可以学习的Python途径...

一百多行python代码实现抢票助手

一. 代码使用Python+Splinter开发,Splinter是一个使用Python开发的开源Web应用测试工具,它可以帮你实现自动浏览站点和与其进行交互。 二. ...

Python切片操作实例分析

本文实例讲述了Python切片操作。分享给大家供大家参考,具体如下: 在很多编程语言中,针对字符串提供了截取函数,其实目的就是对字符串切片。Python没有针对字符串的截取函数,只需要切...

python益智游戏计算汉诺塔问题示例

汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大...