Writing IP addresses on file, each IP on a different line using Python

1
from scapy.all import *


pkts = rdpcap("lalalao.pcap")

for p in pkts:
##  print p.time


        if IP in p: #if packet has IP layer
                    src_ip = p[IP].src
                    dest_ip = p[IP].dst
                    print src_ip

                    f = open('IP_src.txt', 'a+')
                    for ip in src_ip:
                            f.writelines(ip)

                    f.close()

The above code correctly prints one src_ip per line:

216.58.202.229
216.58.202.229
192.168.1.3
216.58.202.229
216.58.202.229
192.168.1.3
216.58.202.229
216.58.202.229
192.168.1.3
216.58.202.229
192.168.1.3
216.58.202.229

But at the time of saving in the IP_src.txt file, the file gets all messed up, all on the same line. How to save src_ip in file one per line? When I pass this file to another program read, does it give any problem that the src_ip are one per line? Is there a difference between python 2 and python 3 at this point?

    
asked by anonymous 05.03.2017 / 05:17

1 answer

2

You have failed to insert the line break "\ n", you can use .write("\n") for example:

from scapy.all import *


pkts = rdpcap("lalalao.pcap")

for p in pkts:
    ##  print p.time


    if IP in p: #if packet has IP layer
        src_ip = p[IP].src
        dest_ip = p[IP].dst
        print src_ip

        f = open('IP_src.txt', 'w')
        for ip in src_ip:
            f.write(ip + "\n")

        f.close()
    
05.03.2017 / 05:38