2017-07-20 35 views
1

所以我想在發送多個數據包又一遍我的虛擬機,但一次嘗試之後,我得到的錯誤:再發送數據

Traceback (most recent call last): 
    File "SMB_Test2.py", line 157, in <module> 
    s.sendall(SMB_COM_NEGOTIATE) 
    File "C:\Python27\Lib\socket.py", line 228, in meth 
    return getattr(self._sock,name)(*args) 
socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host 

,我推測是由於重複畸形數據被髮送(有意),但我想知道是否以及如何解決這個問題。我基本上希望多次發送SMB_COM_NEGOTIATE。提前致謝。

import socket 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((addr, port)) 
s.settimeout(2) 

print '[*] Connected to "%s:%d".' % (addr, port) 
s.sendall(SMB_COM_NEGOTIATE) 
a = 0 
while a != 50000: 
    print a 
    a = a + 1 
    s.sendall(SMB_COM_NEGOTIATE) 
    print '[*] Sent to "%s:%d".' % (addr, port) 

EDIT(關閉詹姆斯的建議) - 靜止跳轉權利一個錯誤:

a = 0 
try: 
    print "The value of 'a' is %r." % a 
    s.connect((addr, port)) 
    print '[*] Connected to "%s:%d".' % (addr, port) 
    while a != 50000: 
     a = a + 1 
     s.sendall(SMB_COM_NEGOTIATE) 
     print '[*] Sent to "%s:%d".' % (addr, port) 
     print "The value 'a' is %r." % a 
except: 
    print "[-] An error occured!!!" 
    s.close() 
    exit() 

輸出:

The value of 'a' is 0. 
[*] Connected to "192.168.xxx.xxx:xxx". 
[*] Sent to "192.168.xxx.xxx:xxx". 
The value 'a' is 1. 
[-] An error occured!!! 

還試圖此(幾乎相同):

a = 0 
print "The value of 'a' is %r." % a 
s.connect((addr, port)) 
print '[*] Connected to "%s:%d".' % (addr, port) 
def ok(): 
    try: 
     while a != 50000: 
      a = a + 1 
      s.sendall(SMB_COM_NEGOTIATE) 
      print '[*] Sent to "%s:%d".' % (addr, port) 
      print "The value 'a' is %r." % a 
    except: 
     print "[-] An error occured!!!" 
     sleep(0) 
     s.close() 

其中有一個輸出(甚至不發送什麼東西):

The value of 'a' is 0. 
[*] Connected to "192.168.xxx.xxx:xxx". 
[-] An error occurred!!! 
+0

捕獲異常,關閉套接字,獲取一個新套接字並重新連接。在python中查找數以百萬計的文章。 [Here](http://www.pythonforbeginners.com/error-handling/python-try-and-except)就是其中之一。 –

+0

@JamesKPolk更新 – Russell

+0

好吧,顯然「獲得一個新的套接字並再次連接」需要在循環內。 –

回答

0

這是一個代碼片段來說明我的評論。

import socket 

def try_connect(): 
    """Tries to connect and send the SMB_COM_NEGOTIATE bytes. 
     Returns the socket object on success and None on failure. 
    """ 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.settimeout(2) 
    try: 
     s.connect((addr, port)) 
     s.sendall(SMB_COM_NEGOTIATE) 
    except socket.timeout as e: 
     # got a socket timeout 
     return None 
    except OSError as e: 
     # got some other socket error 
     return None 
    return s 

def try_connect_n_times(n): 
    """Try up to n times to connect""" 
    for attempt in range(n): 
     s = try_connect() 
     if s: 
      return s 
    return None 

try_connect_n_times(5000) 
+0

感謝您的幫助文章,完全按照我想要的那樣工作,因爲我刪除了s =並且如果s:return s。感謝您的時間和幫助,非常感謝:)。 – Russell

+0

如果您有興趣,請回答以下問題:我希望每次調用它時都會發送一個新的s.sendall(SMB_COM_NEGOTIATE)。我試過用def來調用它,但這並不起作用(用wireshark分析)。想法? – Russell