Python查看远程主机端口是否开放以及BashShell实现
2016-06-04 15:51
501 查看
无论是选择Python还是选择Bash Shell都可以很容易检测远程主机端口是否开放,下面的Python例子纯属锦上添花,仅供参考!
源码可参见Github:https://raw.githubusercontent.com/DingGuodong/LinuxBashShellScriptForOps/master/functions/net/tcp/port/checkRemoteHostPortStatus.py
使用方法:如果用户使用不带参数的方式执行,则需要用户修改Python脚本参数host和port,如果用户使用带参数的方式执行则需要加host和port默认用空格隔开或者参考usage()函数。
源码如下:
--end--
本文出自 “通信,我的最爱” 博客,请务必保留此出处http://dgd2010.blog.51cto.com/1539422/1786096
源码可参见Github:https://raw.githubusercontent.com/DingGuodong/LinuxBashShellScriptForOps/master/functions/net/tcp/port/checkRemoteHostPortStatus.py
使用方法:如果用户使用不带参数的方式执行,则需要用户修改Python脚本参数host和port,如果用户使用带参数的方式执行则需要加host和port默认用空格隔开或者参考usage()函数。
源码如下:
#!/usr/bin/python # encoding: utf-8 # -*- coding: utf8 -*- import socket import sys # import os import time def usage(): print(""" Function: check remote host's tcp port if is open Usage: %s <host ipaddress> <tcp port> Example: python %s 127.0.0.1 22 Others useful cli: strace time: strace -q -f -c python checkRemoteHostPortStatus.py 127.0.0.1 22 Bash shell implement: nc -w 3 127.0.0.1 22 >/dev/null 2>&1 && echo ok || echo failed nmap 127.0.0.1 -p 22 | grep open >/dev/null 2>&1 && echo ok || echo failed """) % (__file__, sys.argv[0]) sys.exit(0) host = "" port = 0 timeout = 3 retry = 3 argc = len(sys.argv) if not (argc == 1 or argc == 3): print("Error: incorrect number of arguments or unrecognized option") usage() if argc == 1: pass else: if sys.argv[1] is not None: host = sys.argv[1] if sys.argv[2] is not None: port = sys.argv[2] if host == "": print "host is empty, please sign new one." sys.exit(1) if port == 0: print "port is empty, please sign new one." sys.exit(1) else: try: type(int(port)) is not int except ValueError: print type(port) print "type port \"%s\" is not int, please sign new one" % port sys.exit(1) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) for attempt in range(0, retry): try: s.connect((str(host), int(port))) print "connect to server %s port %s successfully!" % (host, port) break except Exception: print "connect to server %s port %s failed in %s times! " % (host, port, attempt + 1) # os.system("sleep 1") time.sleep(1) s.close()tag:python,检测端口,远程端口
--end--
本文出自 “通信,我的最爱” 博客,请务必保留此出处http://dgd2010.blog.51cto.com/1539422/1786096
相关文章推荐
- SQL Server如何启用xp_cmdshell组件
- 第一部分:JDK的源码安装和常用shell操作
- Unit Testing PowerShell Code with Pester
- Pester: Unit Testing for PowerShell
- powershell-无法加载文件,因为在此系统中禁止执行脚本
- bash手册 之重定向原理与实现
- Linux操作系统基础解析之(七)——Bash(Shell)基础知识(4)
- Linux操作系统基础解析之(七)——Bash(Shell)基础知识(3)
- Shell脚本调试技术
- shell if 判断
- HBASE启动脚本/Shell解析
- BASH内置变量
- erlang 多种方法接入远程shell控制台
- shell内建(built in)命令
- 四、Shell输入、输出功能和字符颜色设置
- 三、Shell变量类型和运算符
- Shell文件权限和脚本执行
- 整理的最新WebSHell (php过狗一句话,过狗菜刀,2016过狗一句话,2016php免杀一句话)
- shell-使用getopts指定变量取值
- 通过ant调用shell脚本执行adb命令