问题

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

思路

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

能力越大,责任就越大

写个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. WebView 简介

    WebView 简介 日期: 2013年10月29日 注意: API可能有演进,所以需要看当前时间决定是否有用 继承结构: public class WebView extends AbsoluteL ...

  2. 获取request参数的工具类

    package cn.edu.hactcm.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOE ...

  3. Linux下ipconfig分析及C语言实现

    在linux下使用ifconfigl命令能很方便的查看网卡与网线是否连通,运行ifconfig eth0命令大致输出如下: # ifconfig eth0 eth0 Link encap:Ethern ...

  4. 使用Ext JS,不要使用页面做组件重用,尽量不要做页面跳转

    今天,有人请教我处理办法,问题是: 一个Grid,选择某条记录后,单击编辑后,弹出编辑窗口(带编辑表单),编辑完成后单击保存按钮保存表单,并关闭窗口,刷新Grid. 这,本来是很简单的,但囿于开发人员 ...

  5. SMO实现

    #include "stdio.h" #include <vector> using namespace std; float function(float alfa[ ...

  6. OpenCV中OpenMP的使用

    vs2010中调用openMP,并添加头文件#include<omp.h> 代码来源: 作者:gnuhpc 出处:http://www.cnblogs.com/gnuhpc/ #inclu ...

  7. gcc学习(一)[第二版]

    gcc简介 1. gcc是GNU Compiler Collection的缩写.最初是作为C语言的编译器(GNU C  Compiler),作者为Richard Stallman,是GNU项目的奠基者 ...

  8. cocos2d-x项目与vs2013编译

    cocos2d-x项目与vs2013编译 2014-12-17 cheungmine 因为C++11引入了众多开源软件的特性,导致cocos2d-x r3.3项目无法用 vs2010编译. 所以安装了 ...

  9. 内核调试工具 — kdump & crash

    kdump简介 kdump是系统崩溃的时候,用来转储运行内存的一个工具. 系统一旦崩溃,内核就没法正常工作了,这个时候将由kdump提供一个用于捕获当前运行信息的内核, 该内核会将此时内存中的所有运行 ...

  10. ITU-T Technical Paper: QoS 的参数(非常的全,共计88个)

    本文翻译自ITU-T的Technical Paper:<How to increase QoS/QoE of IP-based platform(s) to regionally agreed ...