问题

最近自己服务器访问别人的服务器,有时候会报超时错误,有时候又能够正常访问别人服务器。

思路

最开始猜测是网络不稳定造成的,但是自己没有收集什么时候超时,什么时候能正常访问别人服务器的日志,搞网络运维的同学根本不鸟我(其实,这活本来就是运维的事,有点小心塞,不过想起蜘蛛侠的名言)。

能力越大,责任就越大

写个python脚本,然后,在python脚本里面使用telnet去连接别人服务器对应的端口,然后,计算连接前后的时间长短。

解决

import os
import csv
import time
import argparse
import telnetlib
from datetime import datetime

# 测试远程服务端口连接耗时
# python3 windows_telnet.py 192.168.10.21 80

parser = argparse.ArgumentParser()
parser.add_argument("ip", type=str, help="ip")
parser.add_argument("port", type=str, help="port")
args = parser.parse_args()

timeFormat = "%Y-%m-%d %H:%M:%S.%f"

starTimeTitle = "开始连接时间"
endTimeTitle = "结束连接时间"
differenceTimeTitle = "连接总耗时"

while True:
    starTime = datetime.now()
    starTimeView = starTime.strftime(timeFormat)
    print("开始连接:{0}".format(starTimeView))
    tn = telnetlib.Telnet(args.ip, args.port)
    endTime = datetime.now()
    endTimeView = endTime.strftime(timeFormat)
    print("连接完成:{0}".format(endTimeView))
    tn.close()
    print("连接结束")
    differenceTime = endTime -  starTime
    print("连接消耗:{0}".format(differenceTime))
    nowTime = datetime.now()
    csvFileName = "{0}.csv".format(nowTime.strftime("%Y-%m-%d"))
    if os.path.exists(csvFileName) is not True:
        with open(csvFileName, "w", newline="") as csvfile:
            fieldnames = [starTimeTitle, endTimeTitle, differenceTimeTitle]
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()

    with open(csvFileName, "a", newline="") as csvfile:
        fieldnames = [starTimeTitle, endTimeTitle, differenceTimeTitle]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow({starTimeTitle : starTimeView, endTimeTitle : endTimeView, differenceTimeTitle : differenceTime})

    time.sleep(0.2)

这里涉及到几个Python的知识点:

  • 获取当前时间,计算时间差以及时间格式化
  • telnetlib 的使用
  • 生成csv文件以及对文件读写
  • 在 while True 这个死循环里面需要避免cpu飙到100%问题,则需要在最后一行添加 time.sleep(0.2) 
    接下来一个一个谈这些点:

Python3获取当前时间

from datetime import datetime
starTime = datetime.now()
 endTime = datetime.now()

这样获取出来的时间,我们一般需要在进行格式化处理才能够展现给用户看。

Python3时间格式化

在上面的基础上,我们可以,这样做

timeFormat = "%Y-%m-%d %H:%M:%S.%f"
starTimeView = starTime.strftime(timeFormat)

使用 strftime 方法处理,具体可以查看Python3文档的 date.strftime(format) 部分。

Python3计算时间差

differenceTime = endTime -  starTime

对,就这样相减,就完事了。

telnetlib的使用

import telnetlib
tn = telnetlib.Telnet(")

csv文件创建

import os
import csv
csvFileName = "{0}.csv".format(nowTime.strftime("%Y-%m-%d"))
if os.path.exists(csvFileName) is not True:
    with open(csvFileName, "w", newline="") as csvfile:
        fieldnames = [starTimeTitle, endTimeTitle, differenceTimeTitle]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()

这里是先判断文件是否存在,如果不存在,就创建一个csv文件,并且写好表头。

csv文件追加

with open(csvFileName, "a", newline="") as csvfile:
    fieldnames = [starTimeTitle, endTimeTitle, differenceTimeTitle]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writerow({starTimeTitle : starTimeView, endTimeTitle : endTimeView, differenceTime

死循环避免CPU飚高

循环里面最后添加一行:

import time
time.sleep(0.2)

让线程休眠一段时间,这样就避免死循环占用cpu太高。

使用脚本

python3 windows_telnet.py 192.168.10.21 80

以后就可以通过这个脚本监测远程端口连接问题,并每天生成一个日志文件。

python学习交流群:125240963

原文:https://www.jianshu.com/p/e2e88cbb7572?utm_source=tuicool&utm_medium=referral

Python测试远程端口连接时间的更多相关文章

  1. python检测远程udp端口是否打开的代码

    研发过程,把开发过程较好的代码收藏起来,如下的代码内容是关于python检测远程udp端口是否打开的代码,希望对各朋友有较大帮助. import socketimport threadingimpor ...

  2. Python测试进阶——(2)配置PyCharm远程调试环境

    新建一个Python项目 配置Deployment,用于本地文件和远程文件的同步,在pycharm的菜单栏依次找到:Tools > Deployment > Configuration 点 ...

  3. ssh远程端口转发&&windows系统提权之信息收集&&网安工具分享(部分)

    一.ssh远程端口转发 背景:当我们在渗透过程中,获取到内网的一台仅有内网IP的服务器后,我们可以通过ssh隧道,将内网某个主机的端口进行远程转发 1.网络拓扑图 假设获取的服务器为web服务器,we ...

  4. Python测试 ——开发工具库

    Web UI测试自动化 splinter - web UI测试工具,基于selnium封装. selenium - web UI自动化测试. mechanize- Python中有状态的程序化Web浏 ...

  5. linux 检测远程端口是否打开

    linux 检测远程端口是否打开   检测远程端口是否打开   常用telnet 110.101.101.101 80方式测试远程主机端口是否打开.   除此之外还可以使用:   方法1.nmap i ...

  6. 【译】SSH隧道:本地和远程端口转发

    本文是:SSH Tunnel - Local and Remote Port Forwarding Explained With Examples 的译文 有两种方法可以创建SSH隧道,本地和远程端口 ...

  7. 测试Linux端口的连通性的四种方法

    Linux系统有时候需要测试某个端口的连通性,用户可以参考如下方法来测试.   方法一.telnet法 telnet为用户提供了在本地计算机上完成远程主机工作的能力,因此可以通过telnet来测试端口 ...

  8. Appium环境的安装与配置,Python测试脚本测试

    Appium自动化测试系列1 - Appium环境的安装与配置 发表于4个月前(2015-01-27 14:34)   阅读(803) | 评论(0) 0人收藏此文章, 我要收藏 赞0 寻找 会’偷懒 ...

  9. linux 测试远程主机端口

    检测远程端口是否打开 常用telnet 110.101.101.101 80方式测试远程主机端口是否打开. 除此之外还可以使用: 方法1.nmap ip -p port 测试端口 nmap ip 显示 ...

随机推荐

  1. Uva - 12174 - Shuffle

    用滑动窗口的思想,用一个数组保存每个数在窗口中出现的次数.再用一个变量记录在窗口中恰好出现一次的的数的个数,这样可以枚举所有可能的答案,判断它所对应的所有串口,当且仅当所有的串口均满足要求时这个答案可 ...

  2. C语言中sizeof与strlen区别

    本文转载自:http://www.2cto.com/kf/201109/105100.html 1. 以字符串形式出现的,编译器都会为该字符串自动添加一个0作为结束符,如在代码中写"abc& ...

  3. GCC内联函数:__builtin_types_compatible_p

    #if 0 - Built-in Function: int __builtin_types_compatible_p (type1, type2) You can use the built-in ...

  4. mysql进阶(六)模糊查询的四种用法介绍

    mysql中模糊查询的四种用法介绍 这篇文章主要介绍了mysql中模糊查询的四种用法,需要的朋友可以参考下. 下面介绍mysql中模糊查询的四种用法: 1 %: 表示任意0个或多个字符.可匹配任意类型 ...

  5. ibatis中多表联接查询

     目前,我在做项目的时候,用到了spring + struts2 +ibatis 框架.平时用到的都是一张简单的表,来进行数据的增.删.改.查.而现在突然需要用到其它的一张表,或多张表进行联接查询 ...

  6. LeetCode之“动态规划”:Minimum Path Sum && Unique Paths && Unique Paths II

    之所以将这三道题放在一起,是因为这三道题非常类似. 1. Minimum Path Sum 题目链接 题目要求: Given a m x n grid filled with non-negative ...

  7. 巧用FineReport搭建成本管控监测系统

    一.应用背景 企业在近几年快速发展,规模也越来越大,而信息传递与反馈手段却仍然比较落后,随着信息技术的不断发展,人们开始通过尝试利用技术手段改善这种环境.企业的项目不断增多,而作为高层管理者,通过层级 ...

  8. 图像的基本运算——scale, rotation, translation

    图像是视觉信息的直接反应,图像呈现出各种各样的特效都是通过图像的基本运算来完成的.图像最基本的运算有三种,分别是scale,rotation 和translation,叫做尺度,旋转和平移.很多图像的 ...

  9. PyCharm命令行输入

    PyCharm命令行输入 写作原因 网上资料比较杂,版本较老,与现在的版本有区别,所以根据网上资料和自己亲手实验撰写此文. 设置方法 在菜单中按此路径设置: Run->Edit Configur ...

  10. package.json字段全解

    原文:http://blog.csdn.net/woxueliuyun/article/details/39294375 Name 必须字段. 小提示: 不要在name中包含js, node字样: 这 ...