套接字错误后继续循环

时间:2017-03-17 22:11:18

标签: python sockets

我使用python循环查找开放端口。它应该工作的方式是如果我的列表中的端口打开并接受tcp连接,它将向我发送响应,如果不是,它将跳到下一个端口号。

我遇到的问题是,如果第一个端口没有响应,我从套接字收到错误并且循环停止。这是脚本,包括我的端口列表的定义方式。

import numpy;
import socket;
import sys;

with open("ports.ls") as f:
    ports = f.read().split(",");

portslist = []
for i in ports:
    portslist.append(i.strip());

portslist = [int(i) for i in portslist]

for i in portslist:
    target_host = sys.argv[1];
    target_port = i;
    print "[*] port:%d" % target_port;
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
    client.connect((target_host, i));
    client.send("GET / HTTP/1.1\r\nHost: %s\r\n\r\n" % target_host);
    response = client.recv(4096);
    print response;

我得到的错误是

socket.error: [Errno 11] Resource temporarily unavailable

尽管第一个端口没有响应,我如何继续循环到下一次迭代?

1 个答案:

答案 0 :(得分:0)

假设这是在此脚本中引发的异常,并且未从远程服务器传回,您只需添加异常处理程序即可。

......摆脱分号!

import numpy
import socket
import sys

with open("ports.ls") as f:
    ports = f.read().split(",")

portslist = []
for i in ports:
    portslist.append(i.strip())

portslist = [int(i) for i in portslist]

for i in portslist:
    target_host = sys.argv[1]
    target_port = i
    print "[*] port:%d" % target_port
    try:
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect((target_host, i))
        client.send("GET / HTTP/1.1\r\nHost: %s\r\n\r\n" % target_host)
        response = client.recv(4096)
        print response
    except socket.error as e:
        print e