From b72a0b59db7b6fa0726ffa22da3b88679bffe69c Mon Sep 17 00:00:00 2001 From: gpotter2 <gabriel@potter.fr> Date: Tue, 27 Jun 2017 23:43:42 +0200 Subject: [PATCH] Auto-Fix: refactor print() function --- dev/scripts/autoFixer.py | 9 +++--- scapy/ansmachine.py | 5 +-- scapy/arch/windows/__init__.py | 7 +++-- scapy/arch/windows/compatibility.py | 9 +++--- scapy/asn1/asn1.py | 11 ++++--- scapy/autorun.py | 3 +- scapy/config.py | 3 +- scapy/contrib/dtp.py | 3 +- scapy/contrib/gsm_um.py | 21 +++++++------ scapy/contrib/http2.py | 1 + scapy/contrib/igmp.py | 7 +++-- scapy/contrib/igmpv3.py | 13 ++++---- scapy/dadict.py | 3 +- scapy/layers/dhcp.py | 3 +- scapy/layers/dhcp6.py | 17 ++++++----- scapy/layers/dot11.py | 5 +-- scapy/layers/inet.py | 9 +++--- scapy/layers/inet6.py | 13 ++++---- scapy/layers/l2.py | 5 +-- scapy/layers/snmp.py | 7 +++-- scapy/layers/tls/automaton.py | 45 +++++++++++++-------------- scapy/layers/tls/cert.py | 19 ++++++------ scapy/layers/tls/handshake.py | 11 ++++--- scapy/layers/tls/record.py | 7 +++-- scapy/layers/tls/session.py | 15 ++++----- scapy/main.py | 7 +++-- scapy/modules/p0f.py | 3 +- scapy/packet.py | 23 +++++++------- scapy/pipetool.py | 15 ++++----- scapy/plist.py | 31 ++++++++++--------- scapy/scapypipes.py | 7 +++-- scapy/sendrecv.py | 33 ++++++++++---------- scapy/tools/UTscapy.py | 47 +++++++++++++++-------------- scapy/tools/check_asdis.py | 23 +++++++------- scapy/utils.py | 47 +++++++++++++++-------------- 35 files changed, 261 insertions(+), 226 deletions(-) diff --git a/dev/scripts/autoFixer.py b/dev/scripts/autoFixer.py index ae8e8e10..4959d9bc 100644 --- a/dev/scripts/autoFixer.py +++ b/dev/scripts/autoFixer.py @@ -2,6 +2,7 @@ "Process python files to improve python 3 migration" +from __future__ import print_function import os import sys import getopt @@ -16,8 +17,8 @@ def main(): if not args: raise getopt.error, "At least one file argument required" except getopt.error as msg: - print msg - print "usage:", sys.argv[0], "files ..." + print(msg) + print("usage:", sys.argv[0], "files ...") return files = [] @@ -44,7 +45,7 @@ def process(filename, tabsize): text = f.read() f.close() except IOError as msg: - print "%r: I/O error: %s" % (filename, msg) + print("%r: I/O error: %s" % (filename, msg)) return # Remove tabs newtext = text.expandtabs(tabsize) @@ -59,7 +60,7 @@ def process(filename, tabsize): f = open(filename, "w") f.write(newtext) f.close() - print filename + print(filename) if __name__ == '__main__': main() diff --git a/scapy/ansmachine.py b/scapy/ansmachine.py index eb9bd43e..8c4e511c 100644 --- a/scapy/ansmachine.py +++ b/scapy/ansmachine.py @@ -12,6 +12,7 @@ Answering machines. ######################## from __future__ import absolute_import +from __future__ import print_function from scapy.sendrecv import send,sendp,sniff from scapy.config import conf from scapy.error import log_interactive @@ -100,7 +101,7 @@ class AnsweringMachine(six.with_metaclass(ReferenceAM, object)): self.send_function(reply, **self.optsend) def print_reply(self, req, reply): - print "%s ==> %s" % (req.summary(),reply.summary()) + print("%s ==> %s" % (req.summary(),reply.summary())) def reply(self, pkt): if not self.is_request(pkt): @@ -124,7 +125,7 @@ class AnsweringMachine(six.with_metaclass(ReferenceAM, object)): try: self.sniff() except KeyboardInterrupt: - print "Interrupted by user" + print("Interrupted by user") def sniff(self): sniff(**self.optsniff) diff --git a/scapy/arch/windows/__init__.py b/scapy/arch/windows/__init__.py index b13e7807..63d19bba 100755 --- a/scapy/arch/windows/__init__.py +++ b/scapy/arch/windows/__init__.py @@ -7,6 +7,7 @@ Customizations needed to support Microsoft Windows. """ from __future__ import absolute_import +from __future__ import print_function import os, re, sys, socket, time, itertools, platform import subprocess as sp from glob import glob @@ -353,7 +354,7 @@ class NetworkInterface(object): # No IP detected self.invalid = True except (KeyError, AttributeError, NameError) as e: - print e + print(e) try: self.mac = data['mac'] except KeyError: @@ -499,13 +500,13 @@ class NetworkInterfaceDict(UserDict): def show(self, resolve_mac=True): """Print list of available network interfaces in human readable form""" - print "%s %s %s %s" % ("INDEX".ljust(5), "IFACE".ljust(35), "IP".ljust(15), "MAC") + print("%s %s %s %s" % ("INDEX".ljust(5), "IFACE".ljust(35), "IP".ljust(15), "MAC")) for iface_name in sorted(self.data): dev = self.data[iface_name] mac = dev.mac if resolve_mac: mac = conf.manufdb._resolve_MAC(mac) - print "%s %s %s %s" % (str(dev.win_index).ljust(5), str(dev.name).ljust(35), str(dev.ip).ljust(15), mac) + print("%s %s %s %s" % (str(dev.win_index).ljust(5), str(dev.name).ljust(35), str(dev.ip).ljust(15), mac)) IFACES = NetworkInterfaceDict() IFACES.load_from_powershell() diff --git a/scapy/arch/windows/compatibility.py b/scapy/arch/windows/compatibility.py index c4490f9e..9213c5e0 100644 --- a/scapy/arch/windows/compatibility.py +++ b/scapy/arch/windows/compatibility.py @@ -8,6 +8,7 @@ Instanciate part of the customizations needed to support Microsoft Windows. """ from __future__ import absolute_import +from __future__ import print_function import itertools import os import re @@ -71,13 +72,13 @@ def sndrcv(pks, pkt, timeout = 2, inter = 0, verbose=None, chainCC=0, retry=0, m try: i = 0 if verbose: - print "Begin emission:" + print("Begin emission:") for p in tobesent: pks.send(p) i += 1 time.sleep(inter) if verbose: - print "Finished to send %i packets." % i + print("Finished to send %i packets." % i) except SystemExit: pass except KeyboardInterrupt: @@ -166,7 +167,7 @@ def sndrcv(pks, pkt, timeout = 2, inter = 0, verbose=None, chainCC=0, retry=0, m del(s._answered) if verbose: - print "\nReceived %i packets, got %i answers, remaining %i packets" % (nbrecv+len(ans), len(ans), notans) + print("\nReceived %i packets, got %i answers, remaining %i packets" % (nbrecv+len(ans), len(ans), notans)) return plist.SndRcvList(ans),plist.PacketList(remain,"Unanswered") @@ -229,7 +230,7 @@ stop_filter: python function applied to each packet to determine if prn: r = prn(p) if r is not None: - print r + print(r) if stop_filter and stop_filter(p): break if 0 < count <= c: diff --git a/scapy/asn1/asn1.py b/scapy/asn1/asn1.py index 9f8a6c1a..ab712e18 100644 --- a/scapy/asn1/asn1.py +++ b/scapy/asn1/asn1.py @@ -9,6 +9,7 @@ ASN.1 (Abstract Syntax Notation One) """ from __future__ import absolute_import +from __future__ import print_function import random from datetime import datetime from scapy.config import conf @@ -200,7 +201,7 @@ class ASN1_Object(six.with_metaclass(ASN1_Object_metaclass)): def strshow(self, lvl=0): return (" "*lvl)+repr(self)+"\n" def show(self, lvl=0): - print self.strshow(lvl) + print(self.strshow(lvl)) def __eq__(self, other): return self.val == other def __cmp__(self, other): @@ -280,7 +281,7 @@ class ASN1_BIT_STRING(ASN1_Object): elif name == "val": if isinstance(value, str): if len([c for c in value if c not in ["0", "1"]]) > 0: - print "Invalid operation: 'val' is not a valid bit string." + print("Invalid operation: 'val' is not a valid bit string.") return else: if len(value) % 8 == 0: @@ -297,7 +298,7 @@ class ASN1_BIT_STRING(ASN1_Object): super(ASN1_Object, self).__setattr__(name, value) super(ASN1_Object, self).__setattr__("unused_bits", unused_bits) elif name == "unused_bits": - print "Invalid operation: unused_bits rewriting is not supported." + print("Invalid operation: unused_bits rewriting is not supported.") else: super(ASN1_Object, self).__setattr__(name, value) def __repr__(self): @@ -365,7 +366,7 @@ class ASN1_UTC_TIME(ASN1_STRING): super(ASN1_UTC_TIME, self).__setattr__("pretty_time", pretty_time) super(ASN1_UTC_TIME, self).__setattr__(name, value) elif name == "pretty_time": - print "Invalid operation: pretty_time rewriting is not supported." + print("Invalid operation: pretty_time rewriting is not supported.") else: super(ASN1_UTC_TIME, self).__setattr__(name, value) def __repr__(self): @@ -387,7 +388,7 @@ class ASN1_GENERALIZED_TIME(ASN1_STRING): super(ASN1_GENERALIZED_TIME, self).__setattr__("pretty_time", pretty_time) super(ASN1_GENERALIZED_TIME, self).__setattr__(name, value) elif name == "pretty_time": - print "Invalid operation: pretty_time rewriting is not supported." + print("Invalid operation: pretty_time rewriting is not supported.") else: super(ASN1_GENERALIZED_TIME, self).__setattr__(name, value) def __repr__(self): diff --git a/scapy/autorun.py b/scapy/autorun.py index f8c21ff7..ec4a2356 100644 --- a/scapy/autorun.py +++ b/scapy/autorun.py @@ -7,6 +7,7 @@ Run commands when the Scapy interpreter starts. """ +from __future__ import print_function import code, sys, importlib from scapy.config import conf from scapy.themes import * @@ -60,7 +61,7 @@ def autorun_commands(cmds, my_globals=None, ignore_globals=None, verb=0): sys.stderr.write(str(sys.__dict__.get("ps1",ColorPrompt()))) l = cmds.pop() - print l + print(l) cmd += "\n"+l if interp.runsource(cmd): continue diff --git a/scapy/config.py b/scapy/config.py index 275b6c11..a57bdb3f 100755 --- a/scapy/config.py +++ b/scapy/config.py @@ -8,6 +8,7 @@ Implementation of the configuration object. """ from __future__ import absolute_import +from __future__ import print_function import os,time,socket,sys from scapy import VERSION @@ -168,7 +169,7 @@ class CommandsList(list): return cmd # return cmd so that method can be used as a decorator def lsc(): - print repr(conf.commands) + print(repr(conf.commands)) class CacheInstance(dict): def __init__(self, name="noname", timeout=None): diff --git a/scapy/contrib/dtp.py b/scapy/contrib/dtp.py index e5e247e1..23683c4c 100644 --- a/scapy/contrib/dtp.py +++ b/scapy/contrib/dtp.py @@ -31,6 +31,7 @@ """ from __future__ import absolute_import +from __future__ import print_function from scapy.packet import * from scapy.fields import * from scapy.layers.l2 import SNAP,Dot3,LLC @@ -121,7 +122,7 @@ bind_layers(SNAP, DTP, code=0x2004, OUI=0xc) def negotiate_trunk(iface=conf.iface, mymac=str(RandMAC())): - print "Trying to negotiate a trunk on interface %s" % iface + print("Trying to negotiate a trunk on interface %s" % iface) p = Dot3(src=mymac, dst="01:00:0c:cc:cc:cc")/LLC()/SNAP()/DTP(tlvlist=[DTPDomain(),DTPStatus(),DTPType(),DTPNeighbor(neighbor=mymac)]) sendp(p) diff --git a/scapy/contrib/gsm_um.py b/scapy/contrib/gsm_um.py index 7f370e17..a5bd55d8 100644 --- a/scapy/contrib/gsm_um.py +++ b/scapy/contrib/gsm_um.py @@ -27,6 +27,7 @@ # tested on: scapy-version: 2.2.0 (dev) # #################################################################### +from __future__ import print_function import logging from types import IntType from types import NoneType @@ -67,8 +68,8 @@ def sendum(x, typeSock=0): s.send(x) s.close() except: - print "[Error]: There was a problem when trying to transmit data.\ - Please make sure you started the socket server." + print("[Error]: There was a problem when trying to transmit data.\ + Please make sure you started the socket server.") # Known Bugs/Problems: # If a message uses multiple times the same IE you cannot set the values @@ -127,14 +128,14 @@ def adapt(min_length, max_length, fields, fields2, location=2): def examples(example=None): if example == None: - print """This command presents some example to introduce scapy + print("""This command presents some example to introduce scapy gsm-um to new users. The following parameters can be used: examples("imsiDetach") examples("call") - examples("dissect")""" + examples("dissect")""") elif example == "imsiDetach": - print """ + print(""" >>> a=imsiDetachIndication() ... a.typeOfId=1; a.odd=1; a.idDigit1=0xF; ... a.idDigit2_1=2; a.idDigit2=7; a.idDigit3_1=0; @@ -145,13 +146,13 @@ The following parameters can be used: >>> hexdump(a) 0000 05 01 00 08 F0 27 07 72 00 01 27 75 14 .....'.r..'u. >>> sendum(a) -""" +""") elif example == "call": - print """ + print(""" If you use an USRP and the testcall function this sets up a phonecall: >>> sendum(setupMobileOriginated()) >>> sendum(connectAcknowledge()) -""" +""") # Section 10.2/3 @@ -2932,7 +2933,7 @@ class MobileIdHdr(Packet): p = p[:1] + struct.pack(">B", res[1]) + p[2:] if res[0] != 0: p = p[:-res[0]] - print repr(p) + print(repr(p)) return p + pay @@ -5951,7 +5952,7 @@ class BearerCapabilityHdr(Packet): if len(p) is 5: p = p[:-2] if self.lengthBC is None: - print "len von a %s" % (len(p),) + print("len von a %s" % (len(p),)) p = p[:1] + struct.pack(">B", len(p)-3) + p[2:] return p + pay diff --git a/scapy/contrib/http2.py b/scapy/contrib/http2.py index e87875f9..83b65493 100644 --- a/scapy/contrib/http2.py +++ b/scapy/contrib/http2.py @@ -26,6 +26,7 @@ scapy.contrib.description=HTTP/2 (RFC 7540, RFC 7541) """ from __future__ import absolute_import +from __future__ import print_function import abc import types import re diff --git a/scapy/contrib/igmp.py b/scapy/contrib/igmp.py index a59dcfeb..b533f43c 100644 --- a/scapy/contrib/igmp.py +++ b/scapy/contrib/igmp.py @@ -21,6 +21,7 @@ # TODO: scapy 2 has function getmacbyip, maybe it can replace igmpize # at least from the MAC layer +from __future__ import print_function from scapy.packet import * from scapy.fields import * from scapy.layers.inet import * @@ -162,7 +163,7 @@ IGMPv2 message format http://www.faqs.org/rfcs/rfc2236.html ip.dst = self.gaddr # IP rule 3a retCode = True else: - print "Warning: Using invalid Group Address" + print("Warning: Using invalid Group Address") retCode = False elif ((self.type == 0x17) and isValidMCAddr(self.gaddr)): ip.dst = "224.0.0.2" # IP rule 2 @@ -171,10 +172,10 @@ IGMPv2 message format http://www.faqs.org/rfcs/rfc2236.html ip.dst = self.gaddr # IP rule 3b retCode = True else: - print "Warning: Using invalid IGMP Type" + print("Warning: Using invalid IGMP Type") retCode = False else: - print "Warning: No IGMP Group Address set" + print("Warning: No IGMP Group Address set") retCode = False if retCode == True: ip.ttl=1 # IP Rule 4 diff --git a/scapy/contrib/igmpv3.py b/scapy/contrib/igmpv3.py index 7c8aec25..1469abc9 100644 --- a/scapy/contrib/igmpv3.py +++ b/scapy/contrib/igmpv3.py @@ -17,6 +17,7 @@ # scapy.contrib.description = IGMPv3 # scapy.contrib.status = loads +from __future__ import print_function from scapy.packet import * from scapy.fields import * from scapy.layers.inet import * @@ -40,7 +41,7 @@ from scapy.contrib.igmp import isValidMCAddr # #import sys, socket, struct, time -print "IGMPv3 is still under development - Nov 2010" +print("IGMPv3 is still under development - Nov 2010") class IGMPv3gr(Packet): @@ -71,8 +72,8 @@ class IGMPv3gr(Packet): """ p += pay if self.auxdlen != 0: - print "NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0)." - print " Subsequent Group Records are lost!" + print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).") + print(" Subsequent Group Records are lost!") return p #-------------------------------------------------------------------------- def mysummary(self): @@ -258,7 +259,7 @@ class IGMPv3(Packet): ip.dst = self.gaddr # IP rule 3a retCode = True else: - print "Warning: Using invalid Group Address" + print("Warning: Using invalid Group Address") retCode = False elif ((self.type == 0x17) and isValidMCAddr(self.gaddr)): ip.dst = "224.0.0.2" # IP rule 2 @@ -267,10 +268,10 @@ class IGMPv3(Packet): ip.dst = self.gaddr # IP rule 3b retCode = True else: - print "Warning: Using invalid IGMP Type" + print("Warning: Using invalid IGMP Type") retCode = False else: - print "Warning: No IGMP Group Address set" + print("Warning: No IGMP Group Address set") retCode = False if retCode == True: ip.ttl=1 # IP Rule 4 diff --git a/scapy/dadict.py b/scapy/dadict.py index 2356ed05..57d5f250 100644 --- a/scapy/dadict.py +++ b/scapy/dadict.py @@ -8,6 +8,7 @@ Direct Access dictionary. """ from __future__ import absolute_import +from __future__ import print_function from scapy.error import Scapy_Exception import scapy.modules.six as six @@ -41,7 +42,7 @@ class DADict: def _show(self): for k in self.__dict__.keys(): if k and k[0] != "_": - print "%10s = %r" % (k,getattr(self,k)) + print("%10s = %r" % (k,getattr(self,k))) def __repr__(self): return "<%s/ %s>" % (self._name," ".join(x for x in self.__dict__ if x and x[0]!="_")) diff --git a/scapy/layers/dhcp.py b/scapy/layers/dhcp.py index ccf2fec0..41ee24f5 100644 --- a/scapy/layers/dhcp.py +++ b/scapy/layers/dhcp.py @@ -8,6 +8,7 @@ DHCP (Dynamic Host Configuration Protocol) and BOOTP """ from __future__ import absolute_import +from __future__ import print_function from collections import Iterable import struct @@ -335,7 +336,7 @@ class BOOTP_am(AnsweringMachine): return 1 def print_reply(self, req, reply): - print "Reply %s to %s" % (reply.getlayer(IP).dst,reply.dst) + print("Reply %s to %s" % (reply.getlayer(IP).dst,reply.dst)) def make_reply(self, req): mac = req.src diff --git a/scapy/layers/dhcp6.py b/scapy/layers/dhcp6.py index a404c594..a170db01 100644 --- a/scapy/layers/dhcp6.py +++ b/scapy/layers/dhcp6.py @@ -10,6 +10,7 @@ DHCPv6: Dynamic Host Configuration Protocol for IPv6. [RFC 3315] """ +from __future__ import print_function import socket from scapy.packet import * @@ -1256,7 +1257,7 @@ DHCPv6_am.parse_options( dns="2001:500::1035", domain="localdomain, local", See RFC 4280 for details. If you have a need for others, just ask ... or provide a patch.""" - print msg + print(msg) def parse_options(self, dns="2001:500::1035", domain="localdomain, local", startip="2001:db8::1", endip="2001:db8::20", duid=None, @@ -1273,7 +1274,7 @@ DHCPv6_am.parse_options( dns="2001:500::1035", domain="localdomain, local", l = val.split(',') return [x.strip() for x in l] else: - print "Bad '%s' parameter provided." % param_name + print("Bad '%s' parameter provided." % param_name) self.usage() return -1 @@ -1306,10 +1307,10 @@ DHCPv6_am.parse_options( dns="2001:500::1035", domain="localdomain, local", self.dhcpv6_options[o[2]] = o[3](opt) if self.debug: - print "\n[+] List of active DHCPv6 options:" + print("\n[+] List of active DHCPv6 options:") opts = sorted(self.dhcpv6_options.keys()) for i in opts: - print " %d: %s" % (i, repr(self.dhcpv6_options[i])) + print(" %d: %s" % (i, repr(self.dhcpv6_options[i]))) # Preference value used in Advertise. self.advpref = advpref @@ -1341,7 +1342,7 @@ DHCPv6_am.parse_options( dns="2001:500::1035", domain="localdomain, local", self.duid = DUID_LLT(timeval = timeval, lladdr = mac) if self.debug: - print "\n[+] Our server DUID:" + print("\n[+] Our server DUID:") self.duid.show(label_lvl=" "*4) #### @@ -1360,7 +1361,7 @@ DHCPv6_am.parse_options( dns="2001:500::1035", domain="localdomain, local", if self.debug: - print "\n[+] Starting DHCPv6 service on %s:" % self.iface + print("\n[+] Starting DHCPv6 service on %s:" % self.iface) def is_request(self, p): if not IPv6 in p: @@ -1454,7 +1455,7 @@ DHCPv6_am.parse_options( dns="2001:500::1035", domain="localdomain, local", msg = r + "[DEBUG]" + n + " Received " + g + "Decline" + n msg += " from " + bo + src + vendor + " for " msg += ", ".join(addrs)+ n - print msg + print(msg) # See sect 18.1.7 @@ -1511,7 +1512,7 @@ DHCPv6_am.parse_options( dns="2001:500::1035", domain="localdomain, local", reqsrc = bo + reqsrc + n reptype = g + norm(reply.getlayer(UDP).payload.name) + n - print "Sent %s answering to %s from %s%s" % (reptype, reqtype, reqsrc, vendor) + print("Sent %s answering to %s from %s%s" % (reptype, reqtype, reqsrc, vendor)) def make_reply(self, req): req_mac_src = req.src diff --git a/scapy/layers/dot11.py b/scapy/layers/dot11.py index a1cd53aa..2e33d80d 100644 --- a/scapy/layers/dot11.py +++ b/scapy/layers/dot11.py @@ -7,6 +7,7 @@ Wireless LAN according to IEEE 802.11. """ +from __future__ import print_function import re,struct from zlib import crc32 @@ -432,7 +433,7 @@ iwconfig wlan0 mode managed return [p,q] def print_reply(self): - print self.sprintf("Sent %IP.src%:%IP.sport% > %IP.dst%:%TCP.dport%") + print(self.sprintf("Sent %IP.src%:%IP.sport% > %IP.dst%:%TCP.dport%")) def send_reply(self, reply): sendp(reply, iface=self.ifto, **self.optsend) @@ -490,7 +491,7 @@ iwconfig wlan0 mode managed q.getlayer(TCP).seq+=len(replace) sendp([p,q], iface=ifto, verbose=0) - print p.sprintf("Sent %IP.src%:%IP.sport% > %IP.dst%:%TCP.dport%") + print(p.sprintf("Sent %IP.src%:%IP.sport% > %IP.dst%:%TCP.dport%")) sniff(iface=iffrom,prn=do_airpwn) diff --git a/scapy/layers/inet.py b/scapy/layers/inet.py index 22cbc438..9562e407 100644 --- a/scapy/layers/inet.py +++ b/scapy/layers/inet.py @@ -8,6 +8,7 @@ IPv4 (Internet Protocol v4). """ from __future__ import absolute_import +from __future__ import print_function import os,time,struct,re,socket,new from select import select from collections import defaultdict @@ -43,7 +44,7 @@ class IPTools(object): def whois(self): """whois the source and print the output""" if WINDOWS: - print whois(self.src) + print(whois(self.src)) else: os.system("whois %s" % self.src) def ottl(self): @@ -1650,9 +1651,9 @@ funcpres: a function used to summarize packets""" classes += [t[1] for t in zip(idlst[:-1], idlst[1:]) if abs(t[0]-t[1]) > 50] lst = [(funcID(x), funcpres(x)) for x in lst] lst.sort() - print "Probably %i classes:" % len(classes), classes + print("Probably %i classes:" % len(classes), classes) for id,pr in lst: - print "%5i" % id, pr + print("%5i" % id, pr) @conf.commands.register @@ -1682,7 +1683,7 @@ def fragleak(target,sport=123, dport=123, timeout=0.2, onlyasc=0): if ans.payload.payload.dst != target: continue if ans.src != target: - print "leak from", ans.src, + print("leak from", ans.src, end=' ') # print repr(ans) diff --git a/scapy/layers/inet6.py b/scapy/layers/inet6.py index c372ab91..5c25420e 100644 --- a/scapy/layers/inet6.py +++ b/scapy/layers/inet6.py @@ -25,6 +25,7 @@ IPv6 (Internet Protocol v6). from __future__ import absolute_import +from __future__ import print_function import random import socket import sys @@ -3354,7 +3355,7 @@ def NDP_Attack_DAD_DoS_via_NS(iface=None, mac_src_filter=None, tgt_filter=None, rep = Ether(src=reply_mac)/IPv6(src="::", dst=dst)/ICMPv6ND_NS(tgt=tgt) sendp(rep, iface=iface, verbose=0) - print "Reply NS for target address %s (received from %s)" % (tgt, mac) + print("Reply NS for target address %s (received from %s)" % (tgt, mac)) _NDP_Attack_DAD_DoS(ns_reply_callback, iface, mac_src_filter, tgt_filter, reply_mac) @@ -3415,7 +3416,7 @@ def NDP_Attack_DAD_DoS_via_NA(iface=None, mac_src_filter=None, tgt_filter=None, rep /= ICMPv6NDOptDstLLAddr(lladdr=reply_mac) sendp(rep, iface=iface, verbose=0) - print "Reply NA for target address %s (received from %s)" % (tgt, mac) + print("Reply NA for target address %s (received from %s)" % (tgt, mac)) _NDP_Attack_DAD_DoS(na_reply_callback, iface, mac_src_filter, tgt_filter, reply_mac) @@ -3514,7 +3515,7 @@ def NDP_Attack_NA_Spoofing(iface=None, mac_src_filter=None, tgt_filter=None, received_snma = socket.inet_pton(socket.AF_INET6, dst) expected_snma = in6_getnsma(tgt) if received_snma != expected_snma: - print "solicited node multicast @ does not match target @!" + print("solicited node multicast @ does not match target @!") return 0 return 1 @@ -3540,7 +3541,7 @@ def NDP_Attack_NA_Spoofing(iface=None, mac_src_filter=None, tgt_filter=None, sendp(rep, iface=iface, verbose=0) - print "Reply NA for target address %s (received from %s)" % (tgt, mac) + print("Reply NA for target address %s (received from %s)" % (tgt, mac)) if not iface: iface = conf.iface @@ -3771,7 +3772,7 @@ def NDP_Attack_Kill_Default_Router(iface=None, mac_src_filter=None, sendp(rep, iface=iface, verbose=0) - print "Fake RA sent with source address %s" % src + print("Fake RA sent with source address %s" % src) if not iface: @@ -3856,7 +3857,7 @@ def NDP_Attack_Fake_Router(ra, iface=None, mac_src_filter=None, src = req[IPv6].src sendp(ra, iface=iface, verbose=0) - print "Fake RA sent in response to RS from %s" % src + print("Fake RA sent in response to RS from %s" % src) if not iface: iface = conf.iface diff --git a/scapy/layers/l2.py b/scapy/layers/l2.py index 3b8e57ed..1ee6517b 100644 --- a/scapy/layers/l2.py +++ b/scapy/layers/l2.py @@ -8,6 +8,7 @@ Classes and functions for layer 2 protocols. """ from __future__ import absolute_import +from __future__ import print_function import os, struct, time, socket from scapy.base_classes import Net @@ -1185,7 +1186,7 @@ class ARPingResult(SndRcvList): def show(self): for s,r in self.res: - print r.sprintf("%19s,Ether.src% %ARP.psrc%") + print(r.sprintf("%19s,Ether.src% %ARP.psrc%")) @@ -1291,7 +1292,7 @@ class ARP_am(AnsweringMachine): self.send_function(reply, iface=self.iff, **self.optsend) def print_reply(self, req, reply): - print "%s ==> %s on %s" % (req.summary(),reply.summary(),self.iff) + print("%s ==> %s on %s" % (req.summary(),reply.summary(),self.iff)) @conf.commands.register diff --git a/scapy/layers/snmp.py b/scapy/layers/snmp.py index cb2dc0b7..acd5bf59 100644 --- a/scapy/layers/snmp.py +++ b/scapy/layers/snmp.py @@ -7,6 +7,7 @@ SNMP (Simple Network Management Protocol). """ +from __future__ import print_function from scapy.packet import * from scapy.asn1packet import * from scapy.asn1fields import * @@ -247,12 +248,12 @@ def snmpwalk(dst, oid="1", community="public"): while True: r = sr1(IP(dst=dst)/UDP(sport=RandShort())/SNMP(community=community, PDU=SNMPnext(varbindlist=[SNMPvarbind(oid=oid)])),timeout=2, chainCC=1, verbose=0, retry=2) if ICMP in r: - print repr(r) + print(repr(r)) break if r is None: - print "No answers" + print("No answers") break - print "%-40s: %r" % (r[SNMPvarbind].oid.val,r[SNMPvarbind].value) + print("%-40s: %r" % (r[SNMPvarbind].oid.val,r[SNMPvarbind].value)) oid = r[SNMPvarbind].oid except KeyboardInterrupt: diff --git a/scapy/layers/tls/automaton.py b/scapy/layers/tls/automaton.py index a391929b..8aa0fd70 100644 --- a/scapy/layers/tls/automaton.py +++ b/scapy/layers/tls/automaton.py @@ -24,6 +24,7 @@ t = TLSClientAutomaton(dport=50000, client_hello=ch) t.run() """ +from __future__ import print_function import socket import struct @@ -248,7 +249,7 @@ class TLSClientAutomaton(Automaton): @ATMT.state(final=True) def MISSING_SH(self): - print "Missing TLS Server Hello message" + print("Missing TLS Server Hello message") @ATMT.condition(HANDLE_SH, prio=1) def should_HANDLE_CERT(self): @@ -270,7 +271,7 @@ class TLSClientAutomaton(Automaton): @ATMT.state(final=True) def MISSING_CERT(self): - print "Missing TLS Certificate message" + print("Missing TLS Certificate message") @ATMT.state() def HANDLE_CERT_REQ(self): @@ -549,16 +550,16 @@ class TLSClientAutomaton(Automaton): txt = self.data or "GET /\r\n\r\n" # GET HTTP/1.1\r\n\r\n" p = TLS(type=23, tls_session=self.cur_session, msg=[Raw(load=txt)]) self.socket.send(str(p)) - print "Sent to server: \n%r" % txt + print("Sent to server: \n%r" % txt) self.get_next_msg(1, 0) if self.msg_list: p = self.msg_list[0] self.msg_list = self.msg_list[1:] if isinstance(p, Raw): - print "Received from server: \n%s" % p.load + print("Received from server: \n%s" % p.load) else: - print "Received from server: \n%s" % p + print("Received from server: \n%s" % p) @ATMT.state() def TESTED_CONNECTION(self): @@ -581,7 +582,7 @@ class TLSClientAutomaton(Automaton): try: self.socket.send(str(self.cur_pkt)) except: - print "Could not send termination Alert (maybe the server stopped)" + print("Could not send termination Alert (maybe the server stopped)") self.cur_pkt = None @ATMT.state() @@ -731,8 +732,8 @@ class TLSServerAutomaton(Automaton): s.bind((self.local_ip, self.local_port)) s.listen(1) except: - print "Unable to bind on address %s and port %d" % (self.local_ip, - self.local_port) + print("Unable to bind on address %s and port %d" % (self.local_ip, + self.local_port)) return self.socket, addr = s.accept() if not isinstance(addr, tuple): @@ -789,7 +790,7 @@ class TLSServerAutomaton(Automaton): """ If there is no available cipher suite, close the session with an Alert. """ - print "No usable cipher suite, closing connection" + print("No usable cipher suite, closing connection") self.cur_pkt = TLS(type=21, msg=[], tls_session=self.cur_session) p = TLSAlert(level=1, descr=0) self.cur_pkt.msg.append(p) @@ -802,7 +803,7 @@ class TLSServerAutomaton(Automaton): @ATMT.state(final=True) def MISSING_CH(self): - print "Missing TLS Client Hello message" + print("Missing TLS Client Hello message") @ATMT.condition(HANDLE_CH, prio=2) def should_REPLY_TO_CH(self): @@ -837,8 +838,8 @@ class TLSServerAutomaton(Automaton): self.cur_session.tls_version = self.cur_pkt.version #XXX there should be some checks on this version from the ClientHello v = self.cur_session.tls_version - print "\nVersion: " + _tls_version[v] - print "Cipher suite: " + _tls_cipher_suites[c] + print("\nVersion: " + _tls_version[v]) + print("Cipher suite: " + _tls_cipher_suites[c]) self.cur_pkt = TLS(tls_session=self.cur_session, msg=[]) @@ -889,7 +890,7 @@ class TLSServerAutomaton(Automaton): @ATMT.state() def HANDLE_ALERT_INSTEAD_OF_CKE(self): - print "Received Alert message instead of CKE" + print("Received Alert message instead of CKE") @ATMT.condition(SENT_SH, prio=3) def should_HANDLE_MISSING_CKE(self): @@ -897,7 +898,7 @@ class TLSServerAutomaton(Automaton): @ATMT.state() def HANDLE_MISSING_CKE(self): - print "Missing CKE in client's reply" + print("Missing CKE in client's reply") @ATMT.condition(HANDLE_CKE, prio=1) @@ -927,7 +928,7 @@ class TLSServerAutomaton(Automaton): @ATMT.state() def HANDLE_ALERT_INSTEAD_OF_CCS(self): - print "Received Alert message instead of CCS" + print("Received Alert message instead of CCS") @ATMT.condition(HANDLE_CKE, prio=3) def should_HANDLE_MISSING_CCS(self): @@ -935,7 +936,7 @@ class TLSServerAutomaton(Automaton): @ATMT.state() def HANDLE_MISSING_CCS(self): - print "Missing CCS in client's reply" + print("Missing CCS in client's reply") @ATMT.condition(HANDLE_CCS, prio=1) def should_HANDLE_Finished(self): @@ -963,7 +964,7 @@ class TLSServerAutomaton(Automaton): @ATMT.state() def HANDLE_ALERT_INSTEAD_OF_FINISHED(self): - print "Received Alert message instead of Finished" + print("Received Alert message instead of Finished") @ATMT.condition(HANDLE_CCS, prio=3) def should_HANDLE_MISSING_FINISHED(self): @@ -971,7 +972,7 @@ class TLSServerAutomaton(Automaton): @ATMT.state() def HANDLE_MISSING_FINISHED(self): - print "Missing Finished in client's reply" + print("Missing Finished in client's reply") @ATMT.condition(HANDLE_FINISHED, prio=1) def should_SEND_CCS(self): @@ -1002,7 +1003,7 @@ class TLSServerAutomaton(Automaton): self.get_next_msg() if self.msg_list: return - print "Client left. Closing connection..." + print("Client left. Closing connection...") raise self.FINAL() @ATMT.condition(FINISHED_SENT, prio=1) @@ -1017,8 +1018,8 @@ class TLSServerAutomaton(Automaton): def HANDLE_ALERT_FROM_FINISHED_SENT(self): self.cur_pkt = self.msg_list[0] self.msg_list = self.msg_list[1:] - print "Received Alert Message after sending Finished" - print "Closing connection" + print("Received Alert Message after sending Finished") + print("Closing connection") #XXX no support for new connections, for now raise self.FINAL() @@ -1048,7 +1049,7 @@ class TLSServerAutomaton(Automaton): self.msg_list = self.msg_list[1:] recv_data = self.cur_pkt.data - print "Received %s" % repr(recv_data) + print("Received %s" % repr(recv_data)) if recv_data.startswith("GET / HTTP/1."): header = "HTTP/1.1 200 OK\r\n" diff --git a/scapy/layers/tls/cert.py b/scapy/layers/tls/cert.py index d1d2311c..83ef15ec 100644 --- a/scapy/layers/tls/cert.py +++ b/scapy/layers/tls/cert.py @@ -25,6 +25,7 @@ No need for obnoxious openssl tweaking anymore. :) """ from __future__ import absolute_import +from __future__ import print_function import base64 import os import time @@ -723,10 +724,10 @@ class Cert(six.with_metaclass(_CertMaker, object)): f.close() def show(self): - print "Serial: %s" % self.serial - print "Issuer: " + self.issuer_str - print "Subject: " + self.subject_str - print "Validity: %s to %s" % (self.notBefore_str, self.notAfter_str) + print("Serial: %s" % self.serial) + print("Issuer: " + self.issuer_str) + print("Subject: " + self.subject_str) + print("Validity: %s to %s" % (self.notBefore_str, self.notAfter_str)) def __repr__(self): return "[X.509 Cert. Subject:%s, Issuer:%s]" % (self.subject_str, self.issuer_str) @@ -834,11 +835,11 @@ class CRL(six.with_metaclass(_CRLMaker, object)): return False def show(self): - print "Version: %d" % self.version - print "sigAlg: " + self.sigAlg - print "Issuer: " + self.issuer_str - print "lastUpdate: %s" % self.lastUpdate_str - print "nextUpdate: %s" % self.nextUpdate_str + print("Version: %d" % self.version) + print("sigAlg: " + self.sigAlg) + print("Issuer: " + self.issuer_str) + print("lastUpdate: %s" % self.lastUpdate_str) + print("nextUpdate: %s" % self.nextUpdate_str) ###################### diff --git a/scapy/layers/tls/handshake.py b/scapy/layers/tls/handshake.py index 4479fadb..cb872515 100644 --- a/scapy/layers/tls/handshake.py +++ b/scapy/layers/tls/handshake.py @@ -11,6 +11,7 @@ mechanisms which are addressed with keyexchange.py. """ from __future__ import absolute_import +from __future__ import print_function import math from scapy.error import warning @@ -281,7 +282,7 @@ class TLS_Ext_PrettyPacketList(TLS_Ext_Unknown): label_lvl=label_lvl, first_call=False) if first_call and not dump: - print s + print(s) else: return s @@ -1065,13 +1066,13 @@ class TLSServerKeyExchange(_TLSHandshake): """ s = self.tls_session if s.prcs and s.prcs.key_exchange.anonymous: - print "USELESS SERVER KEY EXCHANGE" + print("USELESS SERVER KEY EXCHANGE") if (s.client_random and s.server_random and s.server_certs and len(s.server_certs) > 0): m = s.client_random + s.server_random + str(self.params) sig_test = self.sig._verify_sig(m, s.server_certs[0]) if not sig_test: - print "INVALID SERVER KEY EXCHANGE SIGNATURE" + print("INVALID SERVER KEY EXCHANGE SIGNATURE") ############################################################################### @@ -1188,7 +1189,7 @@ class TLSCertificateVerify(_TLSHandshake): if s.client_certs and len(s.client_certs) > 0: sig_test = self.sig._verify_sig(m, s.client_certs[0]) if not sig_test: - print "INVALID CERTIFICATE VERIFY SIGNATURE" + print("INVALID CERTIFICATE VERIFY SIGNATURE") ############################################################################### @@ -1285,7 +1286,7 @@ class TLSFinished(_TLSHandshake): verify_data = s.rcs.prf.compute_verify_data(con_end, "read", handshake_msg, ms) if self.vdata != verify_data: - print "INVALID TLS FINISHED RECEIVED" + print("INVALID TLS FINISHED RECEIVED") ## Additional handshake messages diff --git a/scapy/layers/tls/record.py b/scapy/layers/tls/record.py index cebe3c21..0705d72a 100644 --- a/scapy/layers/tls/record.py +++ b/scapy/layers/tls/record.py @@ -12,6 +12,7 @@ ApplicationData submessages. For the Handshake type, see tls_handshake.py. See the TLS class documentation for more information. """ +from __future__ import print_function import struct from scapy.config import conf @@ -250,7 +251,7 @@ class TLS(_GenericTLSSessionInheritance): self.decipherable = False return e.args except AEADTagError as e: - print "INTEGRITY CHECK FAILED" + print("INTEGRITY CHECK FAILED") return e.args def _tls_decrypt(self, s): @@ -368,7 +369,7 @@ class TLS(_GenericTLSSessionInheritance): hdr = hdr[:3] + struct.pack('!H', len(cfrag)) is_mac_ok = self._tls_hmac_verify(hdr, cfrag, mac) if not is_mac_ok: - print "INTEGRITY CHECK FAILED" + print("INTEGRITY CHECK FAILED") elif cipher_type == 'stream': # Decrypt @@ -386,7 +387,7 @@ class TLS(_GenericTLSSessionInheritance): hdr = hdr[:3] + struct.pack('!H', len(cfrag)) is_mac_ok = self._tls_hmac_verify(hdr, cfrag, mac) if not is_mac_ok: - print "INTEGRITY CHECK FAILED" + print("INTEGRITY CHECK FAILED") elif cipher_type == 'aead': # Authenticated encryption diff --git a/scapy/layers/tls/session.py b/scapy/layers/tls/session.py index a74dd41a..04b7882a 100644 --- a/scapy/layers/tls/session.py +++ b/scapy/layers/tls/session.py @@ -7,6 +7,7 @@ TLS session handler. """ +from __future__ import print_function import random import socket import struct @@ -101,10 +102,10 @@ class connState(object): def debug_repr(self, name, secret): if conf.debug_tls and secret: - print "%s %s %s: %s" % (self.connection_end, + print("%s %s %s: %s" % (self.connection_end, self.row, name, - repr_hex(secret)) + repr_hex(secret))) def derive_keys(self, client_random="", @@ -378,7 +379,7 @@ class tlsSession(object): self.server_random) self.master_secret = ms if conf.debug_tls: - print "master secret: %s" % repr_hex(ms) + print("master secret: %s" % repr_hex(ms)) def compute_ms_and_derive_keys(self): self.compute_master_secret() @@ -526,7 +527,7 @@ class _tls_sessions(object): def add(self, session): s = self.find(session) if s: - print "TLS session already exists. Not adding..." + print("TLS session already exists. Not adding...") return h = session.hash() @@ -538,7 +539,7 @@ class _tls_sessions(object): def rem(self, session): s = self.find(session) if s: - print "TLS session does not exist. Not removing..." + print("TLS session does not exist. Not removing...") return h = session.hash() @@ -550,10 +551,10 @@ class _tls_sessions(object): for k in self.sessions[h]: if k.eq(session): if conf.tls_verbose: - print "Found Matching session %s" % k + print("Found Matching session %s" % k) return k if conf.tls_verbose: - print "Did not find matching session %s" % session + print("Did not find matching session %s" % session) return None def __repr__(self): diff --git a/scapy/main.py b/scapy/main.py index 40226c0f..dbe06828 100644 --- a/scapy/main.py +++ b/scapy/main.py @@ -8,6 +8,7 @@ Main module for interactive startup. """ from __future__ import absolute_import +from __future__ import print_function import os,sys import glob import types @@ -48,9 +49,9 @@ DEFAULT_STARTUP_FILE = _probe_config_file(".scapy_startup.py") session = None def _usage(): - print """Usage: scapy.py [-s sessionfile] [-c new_startup_file] [-p new_prestart_file] [-C] [-P] + print("""Usage: scapy.py [-s sessionfile] [-c new_startup_file] [-p new_prestart_file] [-C] [-P] -C: do not read startup file - -P: do not read pre-startup file""" + -P: do not read pre-startup file""") sys.exit(0) @@ -113,7 +114,7 @@ def list_contrib(name=None): key = l[p:q].strip() value = l[q+1:].strip() desc[key] = value - print "%(name)-20s: %(description)-40s status=%(status)s" % desc + print("%(name)-20s: %(description)-40s status=%(status)s" % desc) diff --git a/scapy/modules/p0f.py b/scapy/modules/p0f.py index d1f0c3b7..1f288c78 100644 --- a/scapy/modules/p0f.py +++ b/scapy/modules/p0f.py @@ -8,6 +8,7 @@ Clone of p0f passive OS fingerprinting """ from __future__ import absolute_import +from __future__ import print_function import time import struct import os @@ -318,7 +319,7 @@ def prnp0f(pkt): res += pkt.sprintf("\n -> %IP.dst%:%TCP.dport% (%TCP.flags%)") if r[2] is not None: res += " (distance " + str(r[2]) + ")" - print res + print(res) @conf.commands.register def pkt2uptime(pkt, HZ=100): diff --git a/scapy/packet.py b/scapy/packet.py index 2fbca893..fb65a849 100644 --- a/scapy/packet.py +++ b/scapy/packet.py @@ -8,6 +8,7 @@ Packet class. Binding mechanism. fuzz() method. """ from __future__ import absolute_import +from __future__ import print_function import re import time,itertools import copy @@ -67,12 +68,12 @@ class Packet(six.with_metaclass(Packet_metaclass, BasePacket)): @classmethod def upper_bonds(self): for fval,upper in self.payload_guess: - print "%-20s %s" % (upper.__name__, ", ".join("%-12s" % ("%s=%r"%i) for i in six.iteritems(fval))) + print("%-20s %s" % (upper.__name__, ", ".join("%-12s" % ("%s=%r"%i) for i in six.iteritems(fval)))) @classmethod def lower_bonds(self): for lower,fval in six.iteritems(self._overload_fields): - print "%-20s %s" % (lower.__name__, ", ".join("%-12s" % ("%s=%r"%i) for i in six.iteritems(fval))) + print("%-20s %s" % (lower.__name__, ", ".join("%-12s" % ("%s=%r"%i) for i in six.iteritems(fval)))) def _unpickle(self, dlist): """Used to unpack pickling""" @@ -988,7 +989,7 @@ class Packet(six.with_metaclass(Packet_metaclass, BasePacket)): s += self.payload._show_or_dump(dump=dump, indent=indent, lvl=lvl+(" "*indent*self.show_indent), label_lvl=label_lvl, first_call=False) if first_call and not dump: - print s + print(s) else: return s @@ -1383,7 +1384,7 @@ def ls(obj=None, case_sensitive=False, verbose=False): or pattern.search(layer.name or ''))), key=lambda x: x.__name__) for layer in all_layers: - print "%-10s : %s" % (layer.__name__, layer._name) + print("%-10s : %s" % (layer.__name__, layer._name)) else: is_pkt = isinstance(obj, Packet) @@ -1428,18 +1429,18 @@ def ls(obj=None, case_sensitive=False, verbose=False): class_name += " (%d bit%s)" % (cur_fld.size, "s" if cur_fld.size > 1 else "") - print "%-10s : %-35s =" % (f.name, class_name), + print("%-10s : %-35s =" % (f.name, class_name), end=' ') if is_pkt: - print "%-15r" % (getattr(obj, f.name),), - print "(%r)" % (f.default,) + print("%-15r" % (getattr(obj, f.name),), end=' ') + print("(%r)" % (f.default,)) for attr in long_attrs: - print "%-15s%s" % ("", attr) + print("%-15s%s" % ("", attr)) if is_pkt and not isinstance(obj.payload, NoPayload): - print "--" + print("--") ls(obj.payload) else: - print "Not a packet class or name. Type 'ls()' to list packet classes." + print("Not a packet class or name. Type 'ls()' to list packet classes.") @@ -1457,7 +1458,7 @@ def fuzz(p, _inplace=0): for f in q.fields_desc: if isinstance(f, PacketListField): for r in getattr(q, f.name): - print "fuzzing", repr(r) + print("fuzzing", repr(r)) fuzz(r, _inplace=1) elif f.default is not None: rnd = f.randval() diff --git a/scapy/pipetool.py b/scapy/pipetool.py index 4f5e84b6..3da17afd 100644 --- a/scapy/pipetool.py +++ b/scapy/pipetool.py @@ -5,6 +5,7 @@ ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license +from __future__ import print_function import os import subprocess import itertools @@ -30,14 +31,14 @@ class PipeEngine: doc = pc.__doc__ or "" if doc: doc = doc.splitlines()[0] - print "%20s: %s" % (pn, doc) + print("%20s: %s" % (pn, doc)) @classmethod def list_pipes_detailed(cls): for pn,pc in sorted(cls.pipes.items()): if pc.__doc__: - print "###### %s\n %s" % (pn ,pc.__doc__) + print("###### %s\n %s" % (pn ,pc.__doc__)) else: - print "###### %s" % pn + print("###### %s" % pn) def __init__(self, *pipes): self.active_pipes = set() @@ -171,7 +172,7 @@ class PipeEngine: else: warning("Pipe engine thread not running") except KeyboardInterrupt: - print "Interrupted by user." + print("Interrupted by user.") def add(self, *pipes): pipes = self._add_pipes(*pipes) @@ -406,9 +407,9 @@ class ConsoleSink(Sink): +-------+ """ def push(self, msg): - print ">%r" % msg + print(">%r" % msg) def high_push(self, msg): - print ">>%r" % msg + print(">>%r" % msg) class RawConsoleSink(Sink): """Print messages on low and high entries @@ -510,7 +511,7 @@ class TermSink(Sink): _output, _stderr = _p.communicate() # This is the process PID self.__p = int(_output) - print("PID:" + str(self.__p)) + print(("PID:" + str(self.__p))) def _start_unix(self): if not self.opened: self.opened = True diff --git a/scapy/plist.py b/scapy/plist.py index 056f216d..e476756d 100644 --- a/scapy/plist.py +++ b/scapy/plist.py @@ -9,6 +9,7 @@ PacketList: holds several packets and allows to do operations on them. from __future__ import absolute_import +from __future__ import print_function import os,subprocess from collections import defaultdict @@ -100,9 +101,9 @@ lfilter: truth function to apply to each packet to decide whether it will be dis if not lfilter(r): continue if prn is None: - print self._elt2sum(r) + print(self._elt2sum(r)) else: - print prn(r) + print(prn(r)) def nsummary(self, prn=None, lfilter=None): """prints a summary of each packet with the packet's number prn: function to apply to each packet instead of lambda x:x.summary() @@ -111,11 +112,11 @@ lfilter: truth function to apply to each packet to decide whether it will be dis if lfilter is not None: if not lfilter(res): continue - print conf.color_theme.id(i,fmt="%04i"), + print(conf.color_theme.id(i,fmt="%04i"), end=' ') if prn is None: - print self._elt2sum(res) + print(self._elt2sum(res)) else: - print prn(res) + print(prn(res)) def display(self): # Deprecated. Use show() """deprecated. is show()""" self.show() @@ -240,9 +241,9 @@ lfilter: truth function to apply to each packet to decide whether it will be dis p = self._elt2pkt(res) if lfilter is not None and not lfilter(p): continue - print "%s %s %s" % (conf.color_theme.id(i,fmt="%04i"), + print("%s %s %s" % (conf.color_theme.id(i,fmt="%04i"), p.sprintf("%.time%"), - self._elt2sum(res)) + self._elt2sum(res))) if p.haslayer(conf.raw_layer): hexdump(p.getlayer(conf.raw_layer).load) @@ -253,9 +254,9 @@ lfilter: truth function to apply to each packet to decide whether it will be dis p = self._elt2pkt(res) if lfilter is not None and not lfilter(p): continue - print "%s %s %s" % (conf.color_theme.id(i,fmt="%04i"), + print("%s %s %s" % (conf.color_theme.id(i,fmt="%04i"), p.sprintf("%.time%"), - self._elt2sum(res)) + self._elt2sum(res))) hexdump(p) def padding(self, lfilter=None): @@ -264,9 +265,9 @@ lfilter: truth function to apply to each packet to decide whether it will be dis p = self._elt2pkt(res) if p.haslayer(conf.padding_layer): if lfilter is None or lfilter(p): - print "%s %s %s" % (conf.color_theme.id(i,fmt="%04i"), + print("%s %s %s" % (conf.color_theme.id(i,fmt="%04i"), p.sprintf("%.time%"), - self._elt2sum(res)) + self._elt2sum(res))) hexdump(p.getlayer(conf.padding_layer).load) def nzpadding(self, lfilter=None): @@ -278,9 +279,9 @@ lfilter: truth function to apply to each packet to decide whether it will be dis if pad == pad[0]*len(pad): continue if lfilter is None or lfilter(p): - print "%s %s %s" % (conf.color_theme.id(i,fmt="%04i"), + print("%s %s %s" % (conf.color_theme.id(i,fmt="%04i"), p.sprintf("%.time%"), - self._elt2sum(res)) + self._elt2sum(res))) hexdump(p.getlayer(conf.padding_layer).load) @@ -434,7 +435,7 @@ lfilter: truth function to apply to each packet to decide whether it will be dis subprocess.Popen([conf.prog.psreader, filename+".ps"]) else: d.writePSfile(filename) - print + print() def pdfdump(self, filename = None, **kargs): """Creates a PDF file with a psdump of every packet @@ -447,7 +448,7 @@ lfilter: truth function to apply to each packet to decide whether it will be dis subprocess.Popen([conf.prog.pdfreader, filename+".pdf"]) else: d.writePDFfile(filename) - print + print() def sr(self,multi=0): """sr([multi=1]) -> (SndRcvList, PacketList) diff --git a/scapy/scapypipes.py b/scapy/scapypipes.py index b1cbc5b6..4d37f5e1 100644 --- a/scapy/scapypipes.py +++ b/scapy/scapypipes.py @@ -3,6 +3,7 @@ ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license +from __future__ import print_function import socket import Queue from scapy.pipetool import Source,Drain,Sink @@ -44,17 +45,17 @@ class RdpcapSource(Source): self.fname = fname self.f = PcapReader(self.fname) def start(self): - print "start" + print("start") self.f = PcapReader(self.fname) self.is_exhausted = False def stop(self): - print "stop" + print("stop") self.f.close() def fileno(self): return self.f.fileno() def deliver(self): p = self.f.recv() - print "deliver %r" % p + print("deliver %r" % p) if p is None: self.is_exhausted = True else: diff --git a/scapy/sendrecv.py b/scapy/sendrecv.py index c72c8380..1fc6ce38 100644 --- a/scapy/sendrecv.py +++ b/scapy/sendrecv.py @@ -8,6 +8,7 @@ Functions to send and receive packets. """ from __future__ import absolute_import +from __future__ import print_function import errno import os, sys, time, subprocess import itertools @@ -94,13 +95,13 @@ def sndrcv(pks, pkt, timeout = None, inter = 0, verbose=None, chainCC=0, retry=0 try: i = 0 if verbose: - print "Begin emission:" + print("Begin emission:") for p in tobesent: pks.send(p) i += 1 time.sleep(inter) if verbose: - print "Finished to send %i packets." % i + print("Finished to send %i packets." % i) except SystemExit: pass except KeyboardInterrupt: @@ -224,7 +225,7 @@ def sndrcv(pks, pkt, timeout = None, inter = 0, verbose=None, chainCC=0, retry=0 del(s._answered) if verbose: - print "\nReceived %i packets, got %i answers, remaining %i packets" % (nbrecv+len(ans), len(ans), notans) + print("\nReceived %i packets, got %i answers, remaining %i packets" % (nbrecv+len(ans), len(ans), notans)) return plist.SndRcvList(ans),plist.PacketList(remain,"Unanswered") @@ -267,7 +268,7 @@ def __gen_send(s, x, inter=0, loop=0, count=None, verbose=None, realtime=None, r pass s.close() if verbose: - print "\nSent %i packets." % n + print("\nSent %i packets." % n) if return_packets: return sent_packets @@ -435,24 +436,24 @@ def __sr_loop(srfunc, pkts, prn=lambda x:x[1].summary(), prnfail=lambda x:x.summ break count -= 1 start = time.time() - print "\rsend...\r", + print("\rsend...\r", end=' ') res = srfunc(pkts, timeout=timeout, verbose=0, chainCC=1, *args, **kargs) n += len(res[0])+len(res[1]) r += len(res[0]) if verbose > 1 and prn and len(res[0]) > 0: msg = "RECV %i:" % len(res[0]) - print "\r"+ct.success(msg), + print("\r"+ct.success(msg), end=' ') for p in res[0]: - print col(prn(p)) - print " "*len(msg), + print(col(prn(p))) + print(" "*len(msg), end=' ') if verbose > 1 and prnfail and len(res[1]) > 0: msg = "fail %i:" % len(res[1]) - print "\r"+ct.fail(msg), + print("\r"+ct.fail(msg), end=' ') for p in res[1]: - print col(prnfail(p)) - print " "*len(msg), + print(col(prnfail(p))) + print(" "*len(msg), end=' ') if verbose > 1 and not (prn or prnfail): - print "recv:%i fail:%i" % tuple(map(len, res[:2])) + print("recv:%i fail:%i" % tuple(map(len, res[:2]))) if store: ans += res[0] unans += res[1] @@ -463,7 +464,7 @@ def __sr_loop(srfunc, pkts, prn=lambda x:x[1].summary(), prnfail=lambda x:x.summ pass if verbose and n>0: - print ct.normal("\nSent %i packets, received %i packets. %3.1f%% hits." % (n,r,100.0*r/n)) + print(ct.normal("\nSent %i packets, received %i packets. %3.1f%% hits." % (n,r,100.0*r/n))) return plist.SndRcvList(ans),plist.PacketList(unans) @conf.commands.register @@ -530,7 +531,7 @@ def sndrcvflood(pks, pkt, prn=lambda s_r:s_r[1].summary(), chainCC=0, store=1, u continue seen[res] = None if res is not None: - print res + print(res) if store: received.append((i,p)) except KeyboardInterrupt: @@ -653,7 +654,7 @@ interfaces) if prn: r = prn(p) if r is not None: - print r + print(r) if stop_filter and stop_filter(p): stop_event = True break @@ -728,7 +729,7 @@ stop_filter: python function applied to each packet to determine if prn: r = prn(p) if r is not None: - print r + print(r) if stop_filter and stop_filter(p): stop_event = True break diff --git a/scapy/tools/UTscapy.py b/scapy/tools/UTscapy.py index 5b0c6112..1e4c4331 100755 --- a/scapy/tools/UTscapy.py +++ b/scapy/tools/UTscapy.py @@ -8,6 +8,7 @@ Unit testing infrastructure for Scapy """ from __future__ import absolute_import +from __future__ import print_function import sys, getopt, imp, glob, importlib import bz2, base64, os.path, time, traceback, zlib, sha from scapy.consts import WINDOWS @@ -223,7 +224,7 @@ def parse_config_file(config_path, verb=3): with open(config_path) as config_file: data = json.load(config_file, encoding="utf8") if verb > 2: - print >>sys.stderr, "### Loaded config file", config_path + print("### Loaded config file", config_path, file=sys.stderr) def get_if_exist(key, default): return data[key] if key in data else default return Bunch(testfiles=get_if_exist("testfiles", []), onlyfailed=get_if_exist("onlyfailed", False), @@ -268,35 +269,35 @@ def parse_campaign_file(campaign_file): else: if test is None: if l.strip(): - print >>sys.stderr, "Unknown content [%s]" % l.strip() + print("Unknown content [%s]" % l.strip(), file=sys.stderr) else: test.test += l return test_campaign def dump_campaign(test_campaign): - print "#"*(len(test_campaign.title)+6) - print "## %(title)s ##" % test_campaign - print "#"*(len(test_campaign.title)+6) + print("#"*(len(test_campaign.title)+6)) + print("## %(title)s ##" % test_campaign) + print("#"*(len(test_campaign.title)+6)) if test_campaign.sha and test_campaign.crc: - print "CRC=[%(crc)s] SHA=[%(sha)s]" % test_campaign - print "from file %(filename)s" % test_campaign - print + print("CRC=[%(crc)s] SHA=[%(sha)s]" % test_campaign) + print("from file %(filename)s" % test_campaign) + print() for ts in test_campaign: if ts.crc: - print "+--[%s]%s(%s)--" % (ts.name,"-"*max(2,80-len(ts.name)-18),ts.crc) + print("+--[%s]%s(%s)--" % (ts.name,"-"*max(2,80-len(ts.name)-18),ts.crc)) else: - print "+--[%s]%s" % (ts.name,"-"*max(2,80-len(ts.name)-6)) + print("+--[%s]%s" % (ts.name,"-"*max(2,80-len(ts.name)-6))) if ts.keywords: - print " kw=%s" % ",".join(ts.keywords) + print(" kw=%s" % ",".join(ts.keywords)) for t in ts: - print "%(num)03i %(name)s" % t + print("%(num)03i %(name)s" % t) c = k = "" if t.keywords: k = "kw=%s" % ",".join(t.keywords) if t.crc: c = "[%(crc)s] " % t if c or k: - print " %s%s" % (c,k) + print(" %s%s" % (c,k)) #### COMPUTE CAMPAIGN DIGESTS #### @@ -387,12 +388,12 @@ def run_campaign(test_campaign, get_interactive_session, verb=3, ignore_globals= t.result = res t.decode() if verb > 1: - print >>sys.stderr,"%(result)6s %(crc)s %(name)s" % t + print("%(result)6s %(crc)s %(name)s" % t, file=sys.stderr) test_campaign.passed = passed test_campaign.failed = failed if verb: - print >>sys.stderr,"Campaign CRC=%(crc)s SHA=%(sha)s" % test_campaign - print >>sys.stderr,"PASSED=%i FAILED=%i" % (passed, failed) + print("Campaign CRC=%(crc)s SHA=%(sha)s" % test_campaign, file=sys.stderr) + print("PASSED=%i FAILED=%i" % (passed, failed), file=sys.stderr) return failed @@ -583,7 +584,7 @@ def campaign_to_LATEX(test_campaign): #### USAGE #### def usage(): - print >>sys.stderr,"""Usage: UTscapy [-m module] [-f {text|ansi|HTML|LaTeX}] [-o output_file] + print("""Usage: UTscapy [-m module] [-f {text|ansi|HTML|LaTeX}] [-o output_file] [-t testfile] [-T testfile] [-k keywords [-k ...]] [-K keywords [-K ...]] [-l] [-d|-D] [-F] [-q[q]] [-P preexecute_python_code] [-s /path/to/scapy] [-c configfile] @@ -603,7 +604,7 @@ def usage(): -k <kw1>,<kw2>,...\t: include only tests with one of those keywords (can be used many times) -K <kw1>,<kw2>,...\t: remove tests with one of those keywords (can be used many times) -P <preexecute_python_code> -""" +""", file=sys.stderr) raise SystemExit @@ -764,7 +765,7 @@ def main(argv): KW_KO.append(optarg.split(",")) if VERB > 2: - print >>sys.stderr, "### Booting scapy..." + print("### Booting scapy...", file=sys.stderr) try: from scapy import all as scapy except ImportError as e: @@ -778,7 +779,7 @@ def main(argv): raise getopt.GetoptError("cannot import [%s]: %s" % (m,e)) except getopt.GetoptError as msg: - print >>sys.stderr,"ERROR:",msg + print("ERROR:",msg, file=sys.stderr) raise SystemExit autorun_func = { @@ -790,7 +791,7 @@ def main(argv): } if VERB > 2: - print >>sys.stderr,"### Starting tests..." + print("### Starting tests...", file=sys.stderr) glob_output = "" glob_result = 0 @@ -813,7 +814,7 @@ def main(argv): # Execute all files for TESTFILE in TESTFILES: if VERB > 2: - print >>sys.stderr,"### Loading:", TESTFILE + print("### Loading:", TESTFILE, file=sys.stderr) PREEXEC = PREEXEC_DICT[TESTFILE] if TESTFILE in PREEXEC_DICT else GLOB_PREEXEC output, result, campaign = execute_campaign(open(TESTFILE), OUTPUTFILE, PREEXEC, NUM, KW_OK, KW_KO, @@ -829,7 +830,7 @@ def main(argv): break if VERB > 2: - print >>sys.stderr,"### Writing output..." + print("### Writing output...", file=sys.stderr) # Concenate outputs if FORMAT == Format.HTML: glob_output = pack_html_campaigns(runned_campaigns, glob_output, LOCAL, glob_title) diff --git a/scapy/tools/check_asdis.py b/scapy/tools/check_asdis.py index 4be9ef1b..6431d231 100755 --- a/scapy/tools/check_asdis.py +++ b/scapy/tools/check_asdis.py @@ -1,13 +1,14 @@ #! /usr/bin/env python +from __future__ import print_function import getopt def usage(): - print >>sys.stderr,"""Usage: check_asdis -i <pcap_file> [-o <wrong_packets.pcap>] + print("""Usage: check_asdis -i <pcap_file> [-o <wrong_packets.pcap>] -v increase verbosity -d hexdiff packets that differ -z compress output pcap - -a open pcap file in append mode""" + -a open pcap file in append mode""", file=sys.stderr) def main(argv): PCAP_IN = None @@ -40,7 +41,7 @@ def main(argv): raise getopt.GetoptError("Missing pcap file (-i)") except getopt.GetoptError as e: - print >>sys.stderr,"ERROR: %s" % e + print("ERROR: %s" % e, file=sys.stderr) raise SystemExit @@ -58,7 +59,7 @@ def main(argv): LLcls = conf.l2types.get(pcap.linktype) if LLcls is None: - print >>sys.stderr," Unknown link type [%i]. Can't test anything!" % pcap.linktype + print(" Unknown link type [%i]. Can't test anything!" % pcap.linktype, file=sys.stderr) raise SystemExit @@ -73,26 +74,26 @@ def main(argv): except KeyboardInterrupt: raise except Exception as e: - print "Dissection error on packet %i" % i + print("Dissection error on packet %i" % i) failed += 1 else: if p1 == p2: if VERBOSE >= 2: - print "Packet %i ok" % i + print("Packet %i ok" % i) continue else: - print "Packet %i differs" % i + print("Packet %i differs" % i) differ += 1 if VERBOSE >= 1: - print repr(p2d) + print(repr(p2d)) if DIFF: hexdiff(p1,p2) if pcap_out is not None: pcap_out.write(p1) i+=1 correct = i-differ-failed - print "%i total packets. %i ok, %i differed, %i failed. %.2f%% correct." % (i, correct, differ, - failed, i and 100.0*(correct)/i) + print("%i total packets. %i ok, %i differed, %i failed. %.2f%% correct." % (i, correct, differ, + failed, i and 100.0*(correct)/i)) if __name__ == "__main__": @@ -100,4 +101,4 @@ if __name__ == "__main__": try: main(sys.argv[1:]) except KeyboardInterrupt: - print >>sys.stderr,"Interrupted by user." + print("Interrupted by user.", file=sys.stderr) diff --git a/scapy/utils.py b/scapy/utils.py index 1085c3e3..6def3584 100644 --- a/scapy/utils.py +++ b/scapy/utils.py @@ -8,6 +8,7 @@ General utility functions. """ from __future__ import absolute_import +from __future__ import print_function import os, sys, socket, types import random, time import gzip, zlib @@ -97,7 +98,7 @@ def hexdump(x, dump=False): if dump: return s else: - print s + print(s) @conf.commands.register @@ -125,7 +126,7 @@ def linehexdump(x, onlyasc=0, onlyhex=0, dump=False): if dump: return s else: - print s + print(s) @conf.commands.register def chexdump(x, dump=False): @@ -144,7 +145,7 @@ def chexdump(x, dump=False): if dump: return s else: - print s + print(s) @conf.commands.register def hexstr(x, onlyasc=0, onlyhex=0): @@ -217,45 +218,45 @@ def hexdiff(x,y): while not linex[j]: j += 1 xd -= 1 - print colorize[doy-dox]("%04x" % xd), + print(colorize[doy-dox]("%04x" % xd), end=' ') x += xx line=linex else: - print " ", + print(" ", end=' ') if doy: yd = y j = 0 while not liney[j]: j += 1 yd -= 1 - print colorize[doy-dox]("%04x" % yd), + print(colorize[doy-dox]("%04x" % yd), end=' ') y += yy line=liney else: - print " ", + print(" ", end=' ') - print " ", + print(" ", end=' ') cl = "" for j in range(16): if i+j < l: if line[j]: col = colorize[(linex[j]!=liney[j])*(doy-dox)] - print col("%02X" % ord(line[j])), + print(col("%02X" % ord(line[j])), end=' ') if linex[j]==liney[j]: cl += sane_color(line[j]) else: cl += col(sane(line[j])) else: - print " ", + print(" ", end=' ') cl += " " else: - print " ", + print(" ", end=' ') if j == 7: - print "", + print("", end=' ') - print " ",cl + print(" ",cl) if doy or not yy: doy=0 @@ -551,7 +552,7 @@ class Enum_metaclass(type): def export_object(obj): - print gzip.zlib.compress(six.moves.cPickle.dumps(obj,2),9).encode("base64") + print(gzip.zlib.compress(six.moves.cPickle.dumps(obj,2),9).encode("base64")) def import_object(obj=None): if obj is None: @@ -1352,23 +1353,23 @@ def __make_table(yfmtfunc, fmtfunc, endline, list, fxyz, sortx=None, sorty=None, if seplinefunc: sepline = seplinefunc(l, [vx[x] for x in vxk]) - print sepline + print(sepline) fmt = yfmtfunc(l) - print fmt % "", + print(fmt % "", end=' ') for x in vxk: vxf[x] = fmtfunc(vx[x]) - print vxf[x] % x, - print endline + print(vxf[x] % x, end=' ') + print(endline) if seplinefunc: - print sepline + print(sepline) for y in vyk: - print fmt % y, + print(fmt % y, end=' ') for x in vxk: - print vxf[x] % vz.get((x,y), "-"), - print endline + print(vxf[x] % vz.get((x,y), "-"), end=' ') + print(endline) if seplinefunc: - print sepline + print(sepline) def make_table(*args, **kargs): __make_table(lambda l:"%%-%is" % l, lambda l:"%%-%is" % l, "", *args, **kargs) -- GitLab