2015-02-11 61 views
0

我创建的脚本接收原始tcp数据包并将它们捕获到文件中。但问题在于它没有捕获到文件中,并向我发送错误消息:'str'对象没有'写入'属性。有人能告诉我我在做文件处理部分脚本时做错了什么。通过python脚本将原始数据包捕获到输出文件中

import struct 
import socket 
import os 
from struct import * 


#create INET Streaming socket 
try: 
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) 
except socket.error , msg: 
    print 'Socket could not be created. Error Code : ' + str(msg[0]) +  '   Message ' + msg[1] 
    sys.exit() 


#Open a file 

try: 
    file = raw_input("[*] Please provide a name for capture file: \n") 
    FileOpen = open(file, "a") 
    print "\n[*] Capture file %s will be written to %s. " %      (file,os.getcwd()) 

except: 
    print "\n[*] ERROR! There was issue opening your file" 


# receive a packet 
while True: 
    packet = s.recvfrom(65565) 

    #packet string from tuple 
    packet = packet[0] 

    #take first 20 characters for the ip header 
    ip_header = packet[0:20] 

    #now unpack them :) 
    iph = unpack('!BBHHHBBH4s4s' , ip_header) 

    version_ihl = iph[0] 
    version = version_ihl >> 4 
    ihl = version_ihl & 0xF 

    iph_length = ihl * 4 

    ttl = iph[5] 
    protocol = iph[6] 
    s_addr = '111.111.111.111' 
    d_addr = '127.0.0.1' 

    print 'Version : ' + str(version) + ' IP Header Length : ' + str(ihl) + ' TTL : ' + str(ttl) + ' Protocol : ' + str(protocol) + ' Source Address : ' + str(s_addr) + ' Destination Address : ' + str(d_addr) 

    file.write("\n\t[-] Layer 3[-]\n\n[*] Source IP: %s\n[*] Destination IP: %s\n" % (s_addr, d_addr)) 

    tcp_header = packet[iph_length:iph_length+20] 

    #now unpack them :) 
    tcph = unpack('!HHLLBBHHH' , tcp_header) 

    source_port = 1234 
    dest_port = 80 
    sequence = tcph[2] 
    acknowledgement = tcph[3] 
    doff_reserved = tcph[4] 
    tcph_length = doff_reserved >> 4 

    print 'Source Port : ' + str(source_port) + ' Dest Port : ' +  str(dest_port) + ' Sequence Number : ' + str(sequence) + ' Acknowledgement : ' + str(acknowledgement) + ' TCP header length : ' + str(tcph_length) 

    file. write("\n\t[-]Layer 4[-]\n\n[*]Source Port: %s\n[*]Destination Port: %s\n" % (source_port,dest_port)) 

    file.close() 
+0

您正在写入错误的对象。 'FileOpen = open(file,“a”)'应该是'file = open(file,“a”)' – zakjan 2015-02-11 06:34:01

回答

0

您正在写错对象。 FileOpen = open(file, "a")大概应该是​​- zakjan

0

变化file.writeFileOpen.writefile.closeFileOpen.close