Python Forum
save the output from scapy to txt file
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
save the output from scapy to txt file
#1
hello all ...
some one is deleted my membership and my topic i don't know why ??
so ia'm new in python i want to modify this code after run and get the result on terminal save them in a .txt file

this is my code ...

lena = int(raw_input("Enter Number : "))
print(lena)

logging.basicConfig(format='%(asctime)s %(levelname)-5s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
logger = logging.getLogger(__name__)

def long2net(arg):
    if (arg <= 0 or arg >= 0xFFFFFFFF):
        raise ValueError("illegal netmask value", hex(arg))
    return 32 - int(round(math.log(0xFFFFFFFF - arg, 2)))

def to_CIDR_notation(bytes_network, bytes_netmask):
    network = scapy.utils.ltoa(bytes_network)
    netmask = long2net(bytes_netmask)
    net = "%s/%s" % (network, netmask)
    if netmask < 16:
        logger.warn("%s is too big. skipping" % net)
        return None

    return net

def scan_and_print_neighbors(net, interface, timeout=1):
    logger.info("arping %s on %s" % (net, interface))
    try:
        ans, unans = scapy.layers.l2.arping(net, iface=interface, timeout=timeout, verbose=True)
        for s, r in ans.res:
            line = r.sprintf("%Ether.src%  %ARP.psrc%")
            try:
                hostname = socket.gethostbyaddr(r.psrc)
                line += " " + hostname[0]
            except socket.herror:
                # failed to resolve
                pass
            logger.info(line)
    except socket.error as e:
        if e.errno == errno.EPERM:     # Operation not permitted
            logger.error("%s. Did you run as root?", e.strerror)
        else:
            raise
if __name__ == "__main__":
    if lena == 1:
        for network, netmask, _, interface, address in scapy.config.conf.route.routes:
            # skip loopback network and default gw
            if network == 0 or interface == 'lo' or address == '127.0.0.1' or address == '0.0.0.0':
                continue

            if netmask <= 0 or netmask == 0xFFFFFFFF:
                continue

            net = to_CIDR_notation(network, netmask)
            if interface != scapy.config.conf.iface:
                # see http://trac.secdev.org/scapy/ticket/537
                logger.warn("skipping %s because scapy currently doesn't support arping on non-primary network interfaces", net)
                #continue
            if net:
                scan_and_print_neighbors(net, interface)
                repr(network)
                text_file = open("Output.txt", "w")
                text_file.write(repr(network))

            elif lena == 3 :
                print("Bye Bye  ")
Reply
#2
(Oct-09-2017, 05:22 AM)evilcode1 Wrote: some one is deleted my membership and my topic i don't know why ??
Sorry, due to incident with the server last night, forum had to be reverted to a backup and as a result information from the last few hours was lost.

As to your question - currently your scan_and_print_neighbors is only writing to log file. You have two options - (i) this function could return the information you want (at the moment it returns the default None) and you can write this info to a file in the if __name__ == '__main__' block or (ii) you can pass this info to another function that will write it to file.
combination of two is also possible - function from (i) that you call in the if block.
Reply
#3
(Oct-09-2017, 06:17 AM)buran Wrote:
(Oct-09-2017, 05:22 AM)evilcode1 Wrote: some one is deleted my membership and my topic i don't know why ??
Sorry, due to incident with the server last night, forum had to be reverted to a backup and as a result information from the last few hours was lost.

As to your question - currently your scan_and_print_neighbors is only writing to log file. You have two options - (i) this function could return the information you want (at the moment it returns the default None) and you can write this info to a file in the if __name__ == '__main__' block or (ii) you can pass this info to another function that will write it to file.
combination of two is also possible - function from (i) that you call in the if block.

how i can do that ? i m new at python can show my how the code will become !
Reply
#4
you can redirect stdout:
if __name__ == "__main__":
    import sys
    sys.stdout = open('textout.txt', 'w')
    ... rest of your code here ...
    sys.stdout.close()
Reply
#5
(Oct-09-2017, 09:30 AM)Larz60+ Wrote: you can redirect stdout:
if __name__ == "__main__":
    import sys
    sys.stdout = open('textout.txt', 'w')
    ... rest of your code here ...
    sys.stdout.close()

so it should be like this?
if __name__ == "__main__":
	import sys
	sys.stdout = open('textout.txt', 'w')
    if lena == 1:
        for network, netmask, _, interface, address in scapy.config.conf.route.routes:
            # skip loopback network and default gw
            if network == 0 or interface == 'lo' or address == '127.0.0.1' or address == '0.0.0.0':
                continue
                
            if netmask <= 0 or netmask == 0xFFFFFFFF:
                continue
        
        net = to_CIDR_notation(network, netmask)
        if interface != scapy.config.conf.iface:
            # see http://trac.secdev.org/scapy/ticket/537
            logger.warn("skipping %s because scapy currently doesn't support arping on non-primary network interfaces", net)
            #continue
        if net:
            scan_and_print_neighbors(net, interface)
            repr(network)
            
    sys.stdout.close()
    elif lena == 3 :
        print("Bye Bye  ")

@Larz60+
thank u very much it's working <3
Reply
#6
don't you want the close after:
elif lena == 3 :
Reply
#7
hello all i still get this error :(
i think it's from sys.stdout.close() but im new in python i read al lot about this problem but i can't solve it :( can u help me

this is my code :
logging.basicConfig(format='%(asctime)s %(levelname)-5s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
logger = logging.getLogger(__name__)


def long2net(arg):
	if (arg <= 0 or arg >= 0xFFFFFFFF):
		raise ValueError("illegal netmask value", hex(arg))
	return 32 - int(round(math.log(0xFFFFFFFF - arg, 2)))


def to_CIDR_notation(bytes_network, bytes_netmask):
	network = scapy.utils.ltoa(bytes_network)
	netmask = long2net(bytes_netmask)
	net = "%s/%s" % (network, netmask)
	if netmask < 16:
		logger.warn("%s is too big. skipping" % net)
		return None

	return net


def scan_and_print_neighbors(net, interface, timeout=1):
	logger.info("arping %s on %s" % (net, interface))
	try:
		ans, unans = scapy.layers.l2.arping(net, iface=interface, timeout=timeout, verbose=True)
		for s, r in ans.res:
			line = r.sprintf("%Ether.src%  %ARP.psrc%")
			try:
				hostname = socket.gethostbyaddr(r.psrc)
				line += " " + hostname[0]
			except socket.herror:
				# failed to resolve
				pass
			logger.info(line)
	except socket.error as e:
		if e.errno == errno.EPERM:     # Operation not permitted
			logger.error("%s. Did you run as root?", e.strerror)
		else:
			raise

while True:
    lena = int(raw_input("Enter Number : "))
    print(lena)

     
    if __name__ == "__main__":
        import sys
        import os 
        import time
        
        sys.stdout = open('textout.txt', 'w')
        if lena == 1:
            for network, netmask, _, interface, address in scapy.config.conf.route.routes:
                # skip loopback network and default gw
                if network == 0 or interface == 'lo' or address == '127.0.0.1' or address == '0.0.0.0':
                    continue
                    
                if netmask <= 0 or netmask == 0xFFFFFFFF:
                    continue
            
            net = to_CIDR_notation(network, netmask)
            if interface != scapy.config.conf.iface:
                # see http://trac.secdev.org/scapy/ticket/537
                logger.warn("skipping %s because scapy currently doesn't support arping on non-primary network interfaces", net)
                
            if net:
                scan_and_print_neighbors(net, interface)
                sys.stdout.close()
                
                os.system("awk 'NR > 2 {print $2}' textout.txt > last.txt")
                
                os.system("python detect_doublepulsar_smb.py --file last.txt")
                
        elif lena == 3 :
            print("bye Bye")
            break
Reply
#8
You are overwriting the sys.stdout. Choose another name for the object.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
(Oct-10-2017, 09:46 AM)wavic Wrote: You are overwriting the sys.stdout. Choose another name for the object.
sorry which object ? can u explain more in codes
Reply
#10
The intent is to overwrite sys.stdout -- This will redirect text to the file
remove the close

also make sure you imported sys
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sending Packages with Scapy yoda2247 3 3,769 Dec-25-2024, 11:14 PM
Last Post: yoda2247
  Listening on receiving Interface (using scapy) CodyTheCodeNoob 1 3,430 Dec-22-2024, 10:51 PM
Last Post: PolandoFaker
  Read TXT file in Pandas and save to Parquet zinho 2 2,536 Sep-15-2024, 06:14 PM
Last Post: zinho
  Open/save file on Android frohr 0 2,187 Jan-24-2024, 06:28 PM
Last Post: frohr
  how to save to multiple locations during save cubangt 1 2,032 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  save values permanently in python (perhaps not in a text file)? flash77 8 3,800 Jul-07-2023, 05:44 PM
Last Post: flash77
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 3,090 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Save and Close Excel File avd88 0 9,776 Feb-20-2023, 07:19 PM
Last Post: avd88
  Save multiple Parts of Bytearray to File ? lastyle 1 2,230 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  Permission issue when using scapy jao 3 22,754 Feb-05-2022, 06:14 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020