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脚本

微信跳一跳游戏python脚本

微信更新后出来了一块比较火的小游戏,要是一款不涉及到排行的游戏,可能 没人去关注这款游戏。最开自己一直苦练技术,想在微信排行上面装一装,练了好久才跑三百多分。接着在Github(Gith...

python中pika模块问题的深入探究

python中pika模块问题的深入探究

前言 工作中经常用到rabbitmq,而用的语言主要是python,所以也就经常会用到python中的pika模块,但是这个模块的使用,也给我带了很多问题,这里整理一下关于这个模块我在使...

在tensorflow中实现去除不足一个batch的数据

我就废话不多说了,直接上代码吧! #-*- coding:utf-8 -*- import tensorflow as tf import numpy as np value1...

学习python的几条建议分享

熟悉python语言,以及学会python的编码方式。熟悉python库,遇到开发任务的时候知道如何去找对应的模块。知道如何查找和获取第三方的python库,以应付开发任务。 安装开发...

python实现学生管理系统

python实现学生管理系统

python写的简单的学生管理系统,练习python语法。 可以运行在windows和linux下,python 2.7。 #!/usr/local/bin/python #...