Capturing raw packets into an output file through python script
Question: The script that i created receives raw tcp packets and capturing them in a
file. But the problem is it is not capturing into a file and throwing me an
error message: 'str' object has no attribute 'write'. Can someone tell me what
I am doing wrong in file handling part of script.

    
    
    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()
    


Answer: You are writing to wrong object. `FileOpen = open(file, "a")` should probably
be `file = open(file, "a")` – zakjan

