测试端口是否开放的python脚本

原文: https://www.binarytides.com/code-telnet-client-sockets-python/

配置: 120.79.14.81:81/test.php 下面会返回数据。

telnet 80 不能获取到81端口下的web服务的数据。

telnet 81 就可以发送数据了,

nginx 的access.log的日志:

--------------------------------------------------------------------

The telnet client is a simple commandline utility that is used to connect to socket servers and exchange text messages. Here is an example of how to use telnet to connect to google.com and fetch the homepage.

 
$ telnet google.com 80

The above command will connect to google.com on port 80.

$ telnet google.com 80
Trying 74.125.236.69...
Connected to google.com.
Escape character is '^]'.

Now that it is connected, the telnet command can take user input and send to the server, and whatever the server replies with, will be displayed on the terminal. For example send the http GET command and hit enter twice.

GET / HTTP/1.1

Sending the above will generate some response from the server. Now we are going to make a similar telnet program in python. The program is short and simple. To implement a program that takes user input and fetches results from the remote server at the same, requires somekind of parallel processing. Now the obvious solution to this is to use threads. One thread to keep receiving message from server and another to keep taking in user input. But there is another way to do this apart from threads. And that is select function. Select function allows to monitor multiple sockets/streams for readability and will generate an even if any of the sockets is ready.

Lets take a look at the full code. Its less than 50 lines including comments.

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
35
36
37
38
39
40
41
42
43
44
45
46
47
# telnet program example
import socket, select, string, sys
 
#main function
if __name__ == "__main__":
     
    if(len(sys.argv) < 3) :
        print 'Usage : python telnet.py hostname port'
        sys.exit()
     
    host = sys.argv[1]
    port = int(sys.argv[2])
     
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)
     
    # connect to remote host
    try :
        s.connect((host, port))
    except :
        print 'Unable to connect'
        sys.exit()
     
    print 'Connected to remote host'
     
    while 1:
        socket_list = [sys.stdin, s]
         
        # Get the list sockets which are readable
        read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
         
        for sock in read_sockets:
            #incoming message from remote server
            if sock == s:
                data = sock.recv(4096)
                if not data :
                    print 'Connection closed'
                    sys.exit()
                else :
                    #print data
                    sys.stdout.write(data)
             
            #user entered a message
            else :
                msg = sys.stdin.readline()
                s.send(msg)

Small program! Just run it in a terminal like this

$ python telnet.py google.com 80
Connected to remote host

Once connected it shows the connected message. Once the message pops up, its time to type in some message to send to the remote server. Type the same GET message and send by hitting enter twice. Some response should be generated.

The above program does the task of listening for message from remote server and listening for user input at the same time, and without threads.

1
2
3
4
socket_list = [sys.stdin, s]
         
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])

The socket list contains 2 sockets. First is the sys.stdin which is stream for standard input or the user input at the command line. The other one is the socket that is connected to remote server. The select function keeps listening on both of them. It is a blocking function and returns if either of the 2 things happens

1. Server sends a message
2. User hits enter after typing in a message

If the server socket is ready to be read, then just call recv function on it. If the user input is ready to be read then call sys.stdin.readline() function get the user message. Thats all about it.

The telnet client shown above is a minimal one. The actual telnet client has lots of other features which you can try to implement. The above telnet client can be used as a terminal chat client as well with little modifications. Just have to write a chat server. Will come up with a post on that soon.

Note

The above shown program will work only on linux and not on windows. The program uses the select function read the command line input (stdin). On windows the select function cannot read file descriptors. It can only read sockets created inside winsock. The python documentation on selectfunction mentions this

File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock.
Last Updated On : 15th May 2013

Code a simple telnet client using sockets in python的更多相关文章

  1. A Telnet Client Using Expect

    The following expect script achieves a simple telnet client: login -> send command -> exit. Th ...

  2. 转载:Character data is represented incorrectly when the code page of the client computer differs from the code page of the database in SQL Server 2005

    https://support.microsoft.com/en-us/kb/904803 Character data is represented incorrectly when the cod ...

  3. A simple Test Client built on top of ASP.NET Web API Help Page

    Step 1: Install the Test Client package Install the WebApiTestClient package from the NuGet Package ...

  4. Python CODE——Nonblocking I/O client AND Delaying Server

    #!Nonblocking I/O - Chapter 5 -pollclient.py import socket,sys,select port=51423 host='localhost' sp ...

  5. [文摘]Quick Start to Client side COM and Python

    摘自:PyWin32.chm Introduction This documents how to quickly start using COM from Python. It is not a t ...

  6. Segger RTT : Real Time Terminal SRAM 调试解决方法

    http://segger.com/jlink-real-time-terminal.html Real Time Terminal SEGGER's Real Time Terminal (RTT) ...

  7. OData Client Code Generator

    转发. [Tutorial & Sample] How to use OData Client Code Generator to generate client-side proxy cla ...

  8. 【RL-TCPnet网络教程】第32章 RL-TCPnet之Telnet服务器

    第32章      RL-TCPnet之Telnet服务器 本章节为大家讲解RL-TCPnet的Telnet应用,学习本章节前,务必要优先学习第31章的Telnet基础知识.有了这些基础知识之后,再搞 ...

  9. Code Project精彩系列(转)

    Code Project精彩系列(转)   Code Project精彩系列(转)   Applications Crafting a C# forms Editor From scratch htt ...

随机推荐

  1. 洛谷 P4513 小白逛公园-区间最大子段和-分治+线段树区间合并(单点更新、区间查询)

    P4513 小白逛公园 题目背景 小新经常陪小白去公园玩,也就是所谓的遛狗啦… 题目描述 在小新家附近有一条“公园路”,路的一边从南到北依次排着nn个公园,小白早就看花了眼,自己也不清楚该去哪些公园玩 ...

  2. perl相关知识

    转:http://www.runoob.com/perl/perl-cgi-programming.html Perl 是 Practical Extraction and Report Langua ...

  3. PBR Step by Step( 五)Phong反射模型

    Lamertian模型描述了当光源直接照射到粗糙物体表面时,反射光线的分布情况.在现实中,除了直接光照,还有来自周围环境的间接光照. 直接照射到物体表面的光照,又称为局部光照: 间接照射到物体表面的光 ...

  4. 【BZOJ 4031】 4031: [HEOI2015]小Z的房间 (Matrix-Tree Theorem)

    4031: [HEOI2015]小Z的房间 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 1089  Solved: 533 Description ...

  5. HDU 6119 小小粉丝度度熊(Two pointers)

    [题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=6119 [题目大意] 给出一些签到区间和一些补签卡,问可以创造的最长连续签到区间 [题解] 如果我们 ...

  6. 【欧拉函数】BZOJ4173-数学

    [题目大意] [思路] 基本是popoqqq大爷的题解,稍微添加了几句自己的注释,方便理解 同理,如果n%k+m%k<k等价于0 =∑([(n+m)/k]-[n/k]-[m/k])×φ(k) … ...

  7. 解决XP系统访问Win10打印机被拒绝的问题

    打印机是办公室人员经常会用到的设备,为了方便多人使用都会将打印机设置共享,可是会有许多xp系统用户需要访问win10系统上的打印机,这时候却发现拒绝访问无法连接,该如何解决呢? 其实这是win10做的 ...

  8. 最新iOS砸壳方式Frida (Mac OSX)

    1. 安装Frida 首先需要安装Python3,我下载的是 macOS 64-bit installer 安装,因Macbook本机自带python为2.7.x,故需要配置~/.bash_profi ...

  9. iPhone X 适配手机端 H5 页面通用解决方案

    一:本文提供两种解决方案 1.终端解决方案(最优,建议选择) 2.web解决方案 导语: iPhone X的出现,一方面对于整个手机行业的发展极具创新领头羊的作用,另一方面也对现有业务的页面适配带来了 ...

  10. CentOS下KVM克隆完成后修改MAC地址/VMware复制虚拟机修改MAC地址

    克隆完成之后可能mac地址会有冲突,进入KVM删除/etc/udev/rules.d/70-persistent-net.rules中的eth0的配置,接着把eth1改成eth0,并且修改/etc/s ...