服务器之家

服务器之家 > 正文

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

时间:2021-03-20 00:14     来源/作者:wanlifeipeng

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 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程序设计有所帮助。

原文链接:http://www.cnblogs.com/hupeng1234/p/6715237.html

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部