通过python脚本将原始数据包捕获到输出文件中

时间:2015-02-11 06:25:45

标签: file sockets python-2.7 networking

我创建的脚本接收原始tcp数据包并将其捕获到文件中。但问题是它没有捕获到文件中并向我抛出一条错误消息:'str'对象没有属性'write'。有人能告诉我在文件处理部分脚本中我做错了什么。

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

1 个答案:

答案 0 :(得分:0)

你写错了对象。 FileOpen = open(file, "a")应该是file = open(file, "a") - zakjan