简体   繁体   中英

continue loop after socket error

I'm using a python loop for finding open ports. The way it should work is if a port from my list is open and accepting a tcp connection, it will send me a response and if not it will skip to the next port number.

The problem I'm having is if the first port isn't responding, I receive an error from socket and the loop stops. Here's the script including how my ports list is defined.

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;

and the error I get is

socket.error: [Errno 11] Resource temporarily unavailable

How do I continue the loop to the next iteration despite the first port not being responsive?

Assuming that was a exception raised in this script and not passed back from the remote server, you can just add an exception handler.

...and get rid of the semicolons!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM