Tải TL lập trình ptyhon network engginering english version

369 857 0
Tải TL lập trình ptyhon network engginering english version

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Introduction It is an exciting moment for the Python community. After two decades of careful innovation that saw the language gain features such as context managers, generators, and comprehensions in a careful balance with its focus on remaining simple in both its syntax and its concepts, Python is finally taking off. Instead of being seen as a boutique language that can be risked only by topnotch programming shops such as Google and NASA, Python is now experiencing rapid adoption, both in traditional programming roles, such as web application design, and in the vast world of “reluctant programmers,” such as scientists, data specialists, and engineers—people who learn to program not for its own sake but because they must write programs if they are to make progress in their field. The benefits that a simple programming language offers for the occasional or nonexpert programmer cannot, I think, be overstated.

www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index Please use the Bookmarks and Contents at a Glance links to access them www.it-ebooks.info Contents at a Glance About the Authors������������������������������������������������������������������������������������������������������������� xvii About the Technical Reviewers����������������������������������������������������������������������������������������� xix Acknowledgments������������������������������������������������������������������������������������������������������������� xxi Introduction��������������������������������������������������������������������������������������������������������������������� xxiii ■■Chapter 1: Introduction to Client-Server Networking��������������������������������������������������������1 ■■Chapter 2: UDP����������������������������������������������������������������������������������������������������������������17 ■■Chapter 3: TCP�����������������������������������������������������������������������������������������������������������������39 ■■Chapter 4: Socket Names and DNS����������������������������������������������������������������������������������57 ■■Chapter 5: Network Data and Network Errors�����������������������������������������������������������������75 ■■Chapter 6: TLS/SSL����������������������������������������������������������������������������������������������������������93 ■■Chapter 7: Server Architecture��������������������������������������������������������������������������������������115 ■■Chapter 8: Caches and Message Queues�����������������������������������������������������������������������137 ■■Chapter 9: HTTP Clients�������������������������������������������������������������������������������������������������151 ■■Chapter 10: HTTP Servers����������������������������������������������������������������������������������������������169 ■■Chapter 11: The World Wide Web����������������������������������������������������������������������������������183 ■■Chapter 12: Building and Parsing E-Mail����������������������������������������������������������������������223 ■■Chapter 13: SMTP����������������������������������������������������������������������������������������������������������241 ■■Chapter 14: POP������������������������������������������������������������������������������������������������������������259 ■■Chapter 15: IMAP�����������������������������������������������������������������������������������������������������������267 v www.it-ebooks.info ■ Contents at a Glance ■■Chapter 16: Telnet and SSH�������������������������������������������������������������������������������������������289 ■■Chapter 17: FTP�������������������������������������������������������������������������������������������������������������317 ■■Chapter 18: RPC�������������������������������������������������������������������������������������������������������������331 Index���������������������������������������������������������������������������������������������������������������������������������349 vi www.it-ebooks.info Introduction It is an exciting moment for the Python community After two decades of careful innovation that saw the language gain features such as context managers, generators, and comprehensions in a careful balance with its focus on remaining simple in both its syntax and its concepts, Python is finally taking off Instead of being seen as a boutique language that can be risked only by top-notch programming shops such as Google and NASA, Python is now experiencing rapid adoption, both in traditional programming roles, such as web application design, and in the vast world of “reluctant programmers,” such as scientists, data specialists, and engineers—people who learn to program not for its own sake but because they must write programs if they are to make progress in their field The benefits that a simple programming language offers for the occasional or nonexpert programmer cannot, I think, be overstated Python After its debut in 2008, Python went through a couple of years of reworking and streamlining before it was ready to step into the role of its predecessor But as it now enters its second half-decade, it has emerged as the preferred platform for innovation in the Python community Whether one looks at fundamental improvements, like the fact that true Unicode text is now the default string type in Python 3, or at individual improvements, like correct support for SSL, a built-in asyncio framework for asynchronous programming, and tweaks to Standard Library modules large and small, the platform that Python offers the network programmer is in nearly every way improved This is a significant achievement Python was already one of the best languages for making programmers quickly and effectively productive on the modern Internet This book is not a comprehensive guide to switching from Python to Python It will not tell you how to add parentheses to your old print statements, rename Standard Library module imports to their new names, or debug deeply flawed network code that relied on Python 2’s dangerous automatic conversion between byte strings and Unicode strings—conversions that were always based on rough guesswork There are already excellent resources to help you with that transition or even to help you write libraries carefully enough so that their code will work under both Python and Python 3, in case you need to support both audiences Instead, this book focuses on network programming, using Python for every example script and snippet of code at the Python prompt These examples are intended to build a comprehensive picture of how network clients, network servers, and network tools can best be constructed from the tools provided by the language Readers can study the transition from Python to Python by comparing the scripts used in each chapter of the second edition of this book with the listings here in the third edition—both of which are available at https://github.com/brandon-rhodes/fopnp/tree/m/ thanks to the excellent Apress policy of making source code available online The goal in each of the following chapters is simply to show you how Python can best be used to solve modern network programming problems By focusing squarely on how to accomplish things the right way with Python 3, this book hopes to prepare both the programmer who is getting ready to write a new application from the ground up and the programmer preparing to transition an old code base to the new conventions Both programmers should come away knowing what correct networking code looks like in Python and therefore knowing the look and flavor of the kind of code that ought to be their goal xxiii www.it-ebooks.info ■ Introduction Improvements in This Edition There are several improvements by which this book attempts to update the previous edition, beyond the move to Python as its target language and the many updates to both Standard Library and third-party Python modules that have occurred in the past half-decade • Every Python program listing is now written as a module That is, each one performs its imports and defines its functions or classes but then carefully guards any import-time actions inside an if statement that fires only if the module name has the special string value ' main ' indicating that the module is being run as the main program This is a Python best practice that was almost entirely neglected in the previous edition of this book and whose absence made it more difficult for the sample listings to be pulled into real codebases and used to solve reader problems By putting their executable logic at the left margin instead of inside an if statement, the older program listings may have saved a line or two of code, but they gave novice Python programmers far less practice in how to lay out real code • Instead of making ad hoc use of the raw sys.argv list of strings in a bid to interpret the command line, most of the scripts in this book now use the Standard Library argparse module to interpret options and arguments This not only clarifies and documents the semantics that each script expects during invocation but also lets the user of each script use the –h or help query option to receive interactive assistance when launching the script from the Windows or Unix command line • Program listings now make an effort to perform proper resource control by opening files within a controlling with statement that will close the files automatically when it completes In the previous edition, most listings relied instead on the fact that the C Python runtime from the main Python web site usually assures that files are closed immediately thanks to its aggressive reference counting • The listings, for the most part, have transitioned to the modern format() method for performing string interpolation and away from the old modulo operator hack string % tuple that made sense in the 1990s, when most programmers knew the C language, but that is less readable today for new programmers entering the field—and less powerful since individual Python classes cannot override percent formatting like they can with the new kind • The three chapters on HTTP and the World Wide Web (Chapters through 11) have been rewritten from the ground up with an emphasis on better explaining the protocol and on introducing the most modern tools that Python offers the programmer writing for the Web Explanations of the HTTP protocol now use the Requests library as their go-to API for performing client operations, and Chapter 11 has examples in both Flask and Django • The material on SSL/TLS (Chapter 6) has been completely rewritten to match the vast improvement in support that Python delivers for secure applications While the ssl module in Python is a weak half-measure that does not even verify that the server’s certificate matches the hostname to which Python is connecting, the same module in Python presents a much more carefully designed and extensive API that provides generous control over its features This edition of the book is therefore a better resource for the learning programmer simply in terms of how the listings and examples are constructed, even apart from the improvements that Python has made over previous versions of the language xxiv www.it-ebooks.info ■ Introduction The Network Playground The source code to the program listings in this book is available online so that both current owners of this book and potential readers can study them There is a directory for each chapter of this edition of the book You can find the chapter directories here: https://github.com/brandon-rhodes/fopnp/tree/m/py3 But program listings can go only so far toward supporting the curious student of network programming There are many features of network programming that are difficult to explore from a single host machine Thus, the source code repository for the book provides a sample network of 12 machines, each implemented as a Docker container A setup script is provided that builds the images, launches them, and networks them You can find the script and the images in the source code repository here: https://github.com/brandon-rhodes/fopnp/tree/m/playground You can see the 12 machines and their interconnections in Figure The network is designed to resemble a tiny version of the Internet Figure 1.  The network playground’s topology • Representing the typical situation of a client in a home or coffee shop are the client machines behind modemA and modemB that not only offer no services to the Internet but that are in fact not visible on the wider Internet at all They possess merely local IP addresses, which are meaningful only on the subnet that they share with any other hosts in the same home or coffee shop When they make connections to the outside world, those connections will appear to originate from the IP addresses of the modems themselves • Direct connections allow the modems to connect to an isp gateway out on the wider Internet, which is represented by a single backbone router that forwards packets between the networks to which it is connected xxv www.it-ebooks.info ■ Introduction • example.com and its associated machines represent the configuration of a simple service-oriented machine room Here, no network translation or masquerading is taking place The three servers behind example.com have service ports that are fully exposed to client traffic from the Internet • Each of the service machines ftp, mail, and www has correctly configured daemons up and running so that Python scripts from this book can be run on the other machines in the playground to connect successfully to representative examples of each service • All of the service machines have correctly installed TLS certificates (see Chapter 6), and the client machines all have the example.com signing certificate installed as a trusted certificate This means Python scripts demanding true TLS authentication will be able to achieve it The network playground will continue to be maintained as both Python and Docker continue to evolve Instructions will be maintained in the repository for how to download and run the network locally on your own machine, and they will be tweaked based on user reports to make sure that a virtual machine, which offers the playground, can be run by readers on Linux, Mac OS X, and Windows machines With the ability to connect and run commands within any of the playground machines, you will be able to set up packet tracing at whichever point on the network you want to see traffic passing between clients and servers The example code demonstrated in its documentation, combined with the examples and instruction in this book, should help you reach a solid and vivid understanding of how networks help clients and servers communicate xxvi www.it-ebooks.info Chapter Introduction to Client-Server Networking This book explores network programming in the Python language It covers the basic concepts, modules, and third-party libraries that you are likely to use when communicating with remote machines using the most popular Internet communication protocols The book lacks the space to teach you how to program in Python if you have never seen the language before or if you have never even written a computer program at all; it presumes that you have already learned something about Python programming from the many excellent tutorials and books on the subject I hope that the Python examples in the book give you ideas about how to structure and write your own code But I will be using all sorts of advanced Python features without explanation or apology—though, occasionally, I might point out how I am using a particular technique or construction when I think it is particularly interesting or clever On the other hand, this book does not start by assuming you know any networking! As long as you have ever used a web browser or sent an e-mail, you should know enough to start reading this book at the beginning and learn about computer networking along the way I will approach networking from the point of view of an application programmer who is either implementing a network-connected service—such as a web site, an e-mail server, or a networked computer game—or writing a client program that is designed to use such a service Note that you will not, however, learn how to set up or configure networks from this book The disciplines of network design, server room management, and automated provisioning are full topics all on their own, which tend not to overlap with the discipline of computer programming as covered in this particular book While Python is indeed becoming a big part of the provisioning landscape thanks to projects such as OpenStack, SaltStack, and Ansible, you will want to search for books and documentation that are specifically about provisioning and its many technologies if you want to learn more about them The Building Blocks: Stacks and Libraries As you begin to explore Python network programming, there are two concepts that will appear over and over again • The idea of a protocol stack, in which simpler network services are used as the foundation on which to build more sophisticated services • The fact that you will often be using Python libraries of previously written code—whether modules from the built-in standard library that ships with Python or packages from third-party distributions that you download and install—that already know how to speak the network protocol that you want to use www.it-ebooks.info Chapter ■ Introduction to Client-Server Networking In many cases, network programming simply involves selecting and using a library that already supports the network operations that you need to perform The major purposes of this book are to introduce you to several key networking libraries available for Python while also teaching you about the lower-level network services on which those libraries are built Knowing the lower-level material is useful, both so that you understand how the libraries work and so that you will understand what is happening when something at a lower level goes wrong Let’s begin with a simple example Here is a mailing address:   207 N Defiance St Archbold, OH   I am interested in knowing the latitude and longitude of this physical address It just so happens that Google provides a Geocoding API that can perform such a conversion What would you have to to take advantage of this network service from Python? When looking at a new network service that you want to use, it is always worthwhile to start by finding out whether someone has already implemented the protocol—in this case, the Google Geocoding protocol—which your program will need to speak Start by scrolling through the Python Standard Library documentation, looking for anything having to with geocoding   http://docs.python.org/3/library/   Do you see anything about geocoding? No, neither I But it is important for a Python programmer to look through the Standard Library’s table of contents pretty frequently, even if you usually not find what you are looking for, because each read-through will make you more familiar with the services that are included with Python Doug Hellmann’s “Python Module of the Week” blog is another great reference from which you can learn about the capabilities that come with Python thanks to its Standard Library Since in this case the Standard Library does not have a package to help, you can turn to the Python Package Index, an excellent resource for finding all sorts of general-purpose Python packages contributed by other programmers and organizations from across the world You can also, of course, check the web site of the vendor whose service you will be using to see whether it provides a Python library to access it Or, you can a general Google search for Python plus the name of whatever web service you want to use and see whether any of the first few results link to a package that you might want to try In this case, I searched the Python Package Index, which lives at this URL:   https://pypi.python.org/   There I entered geocoding, and I immediately found a package that is named pygeocoder, which provides a clean interface to Google’s geocoding features (though, you will note from its description, it is not vendor-provided but was instead written by someone besides Google)   http://pypi.python.org/pypi/pygeocoder/   This is such a common situation—finding a Python package that sounds like it might already exactly what you want and that you want to try it on your system—that I should pause for a moment and introduce you to the best Python technology for quickly trying a new library: virtualenv! In the old days, installing a Python package was a gruesome and irreversible act that required administrative privileges on your machine and that left your system Python install permanently altered After several months of heavy Python development, your system Python install could become a wasteland of dozens of packages, all installed by hand, and you could even find that new packages you tried to install would break because they were incompatible with the old packages sitting on your hard drive from a project that ended months ago www.it-ebooks.info Foundations of Python Network Programming Third Edition Brandon Rhodes John Goerzen www.it-ebooks.info Foundations of Python Network Programming, Third Edition Copyright © 2014 by Brandon Rhodes and John Goerzen This work is subject to copyright All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer Permissions for use may be obtained through RightsLink at the Copyright Clearance Center Violations are liable to prosecution under the respective Copyright Law ISBN-13 (pbk): 978-1-4302-5854-4 ISBN-13 (electronic): 978-1-4302-5855-1 Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made The publisher makes no warranty, express or implied, with respect to the material contained herein Managing Director: Welmoed Spahr Lead Editor: Michelle Lowman Technical Reviewers: Alexandre Beaulne and Peter Membrey Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan, Jim DeWolf, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Steve Weiss Coordinating Editor: Kevin Walter Developmental Editor: Gary Schwartz Copy Editor: Kim Wimpsett Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc) SSBM Finance Inc is a Delaware corporation For information on translations, please e-mail rights@apress.com, or visit www.apress.com Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ www.it-ebooks.info To my wonderful nieces, Avery, Savannah, and Aila, remembering our bicycle ride and the wild abandon with which they always round the corner and plunge downhill I hope that they always approach life with such fearlessness, whether they wind up doing any network programming or not www.it-ebooks.info Contents About the Authors������������������������������������������������������������������������������������������������������������� xvii About the Technical Reviewers����������������������������������������������������������������������������������������� xix Acknowledgments������������������������������������������������������������������������������������������������������������� xxi Introduction��������������������������������������������������������������������������������������������������������������������� xxiii ■■Chapter 1: Introduction to Client-Server Networking��������������������������������������������������������1 The Building Blocks: Stacks and Libraries������������������������������������������������������������������������������������1 Application Layers�������������������������������������������������������������������������������������������������������������������������4 Speaking a Protocol����������������������������������������������������������������������������������������������������������������������5 A Raw Network Conversation��������������������������������������������������������������������������������������������������������6 Turtles All the Way Down���������������������������������������������������������������������������������������������������������������9 Encoding and Decoding���������������������������������������������������������������������������������������������������������������10 The Internet Protocol�������������������������������������������������������������������������������������������������������������������11 IP Addresses��������������������������������������������������������������������������������������������������������������������������������12 Routing����������������������������������������������������������������������������������������������������������������������������������������13 Packet Fragmentation�����������������������������������������������������������������������������������������������������������������14 Learning More About IP���������������������������������������������������������������������������������������������������������������15 Summary�������������������������������������������������������������������������������������������������������������������������������������16 ■■Chapter 2: UDP����������������������������������������������������������������������������������������������������������������17 Port Numbers������������������������������������������������������������������������������������������������������������������������������18 Sockets����������������������������������������������������������������������������������������������������������������������������������������19 Promiscuous Clients and Unwelcome Replies����������������������������������������������������������������������������������������������������� 23 Unreliability, Backoff, Blocking, and Timeouts����������������������������������������������������������������������������������������������������� 24 vii www.it-ebooks.info ■ Contents Connecting UDP Sockets������������������������������������������������������������������������������������������������������������������������������������� 28 Request IDs: A Good Idea������������������������������������������������������������������������������������������������������������������������������������� 29 Binding to Interfaces�������������������������������������������������������������������������������������������������������������������30 UDP Fragmentation���������������������������������������������������������������������������������������������������������������������32 Socket Options����������������������������������������������������������������������������������������������������������������������������33 Broadcast������������������������������������������������������������������������������������������������������������������������������������34 When to Use UDP������������������������������������������������������������������������������������������������������������������������������������������������� 36 Summary�������������������������������������������������������������������������������������������������������������������������������������36 ■■Chapter 3: TCP�����������������������������������������������������������������������������������������������������������������39 How TCP Works���������������������������������������������������������������������������������������������������������������������������39 When to Use TCP�������������������������������������������������������������������������������������������������������������������������40 What TCP Sockets Mean�������������������������������������������������������������������������������������������������������������41 A Simple TCP Client and Server��������������������������������������������������������������������������������������������������42 One Socket per Conversation������������������������������������������������������������������������������������������������������������������������������ 45 Address Already in Use���������������������������������������������������������������������������������������������������������������������������������������� 46 Binding to Interfaces�������������������������������������������������������������������������������������������������������������������47 Deadlock�������������������������������������������������������������������������������������������������������������������������������������48 Closed Connections, Half-Open Connections������������������������������������������������������������������������������53 Using TCP Streams Like Files������������������������������������������������������������������������������������������������������54 Summary�������������������������������������������������������������������������������������������������������������������������������������54 ■■Chapter 4: Socket Names and DNS����������������������������������������������������������������������������������57 Hostnames and Sockets��������������������������������������������������������������������������������������������������������������57 Five Socket Coordinates�������������������������������������������������������������������������������������������������������������������������������������� 58 IPv6���������������������������������������������������������������������������������������������������������������������������������������������������������������������� 59 Modern Address Resolution��������������������������������������������������������������������������������������������������������60 Using getaddrinfo( ) to Bind Your Server to a Port����������������������������������������������������������������������������������������������� 61 Using getaddrinfo( ) to Connect to a Service������������������������������������������������������������������������������������������������������� 62 Asking getaddrinfo( ) for a Canonical Hostname�������������������������������������������������������������������������������������������������� 63 viii www.it-ebooks.info ■ Contents Other getaddrinfo( ) Flags������������������������������������������������������������������������������������������������������������������������������������ 64 Primitive Name Service Routines������������������������������������������������������������������������������������������������������������������������ 65 Using getsockaddr( ) in Your Own Code��������������������������������������������������������������������������������������������������������������� 65 The DNS Protocol������������������������������������������������������������������������������������������������������������������������67 Why Not to Use Raw DNS������������������������������������������������������������������������������������������������������������������������������������ 69 Making a DNS Query from Python����������������������������������������������������������������������������������������������������������������������� 69 Resolving Mail Domains�������������������������������������������������������������������������������������������������������������������������������������� 71 Summary�������������������������������������������������������������������������������������������������������������������������������������73 ■■Chapter 5: Network Data and Network Errors�����������������������������������������������������������������75 Bytes and Strings������������������������������������������������������������������������������������������������������������������������75 Character Strings������������������������������������������������������������������������������������������������������������������������������������������������� 76 Binary Numbers and Network Byte Order����������������������������������������������������������������������������������������������������������� 79 Framing and Quoting�������������������������������������������������������������������������������������������������������������������81 Pickles and Self-delimiting Formats�������������������������������������������������������������������������������������������86 XML and JSON�����������������������������������������������������������������������������������������������������������������������������86 Compression�������������������������������������������������������������������������������������������������������������������������������87 Network Exceptions��������������������������������������������������������������������������������������������������������������������88 Raising More Specific Exceptions����������������������������������������������������������������������������������������������������������������������� 90 Catching and Reporting Network Exceptions������������������������������������������������������������������������������������������������������ 91 Summary�������������������������������������������������������������������������������������������������������������������������������������92 ■■Chapter 6: TLS/SSL����������������������������������������������������������������������������������������������������������93 What TLS Fails to Protect������������������������������������������������������������������������������������������������������������93 What Could Possibly Go Wrong?��������������������������������������������������������������������������������������������������94 Generating Certificates����������������������������������������������������������������������������������������������������������������95 Offloading TLS�����������������������������������������������������������������������������������������������������������������������������98 Python 3.4 Default Contexts��������������������������������������������������������������������������������������������������������99 Variations on Socket Wrapping�������������������������������������������������������������������������������������������������������������������������� 103 ix www.it-ebooks.info ■ Contents Hand-Picked Ciphers and Perfect Forward Security�����������������������������������������������������������������104 Protocol Support for TLS�����������������������������������������������������������������������������������������������������������106 Learning Details������������������������������������������������������������������������������������������������������������������������107 Summary�����������������������������������������������������������������������������������������������������������������������������������113 ■■Chapter 7: Server Architecture��������������������������������������������������������������������������������������115 A Few Words About Deployment�����������������������������������������������������������������������������������������������115 A Simple Protocol����������������������������������������������������������������������������������������������������������������������117 A Single-Threaded Server���������������������������������������������������������������������������������������������������������120 Threaded and Multiprocess Servers�����������������������������������������������������������������������������������������123 The Legacy SocketServer Framework��������������������������������������������������������������������������������������������������������������� 124 Async Servers���������������������������������������������������������������������������������������������������������������������������125 Callback-Style asyncio�������������������������������������������������������������������������������������������������������������������������������������� 128 Coroutine-Style asyncio������������������������������������������������������������������������������������������������������������������������������������� 130 The Legacy Module asyncore���������������������������������������������������������������������������������������������������������������������������� 131 The Best of Both Worlds������������������������������������������������������������������������������������������������������������������������������������ 133 Running Under inetd������������������������������������������������������������������������������������������������������������������133 Summary�����������������������������������������������������������������������������������������������������������������������������������135 ■■Chapter 8: Caches and Message Queues�����������������������������������������������������������������������137 Using Memcached���������������������������������������������������������������������������������������������������������������������137 Hashing and Sharding���������������������������������������������������������������������������������������������������������������140 Message Queues�����������������������������������������������������������������������������������������������������������������������142 Using Message Queues from Python����������������������������������������������������������������������������������������������������������������� 144 Summary�����������������������������������������������������������������������������������������������������������������������������������148 ■■Chapter 9: HTTP Clients�������������������������������������������������������������������������������������������������151 Python Client Libraries��������������������������������������������������������������������������������������������������������������151 Ports, Encryption, and Framing�������������������������������������������������������������������������������������������������153 Methods������������������������������������������������������������������������������������������������������������������������������������154 Paths and Hosts������������������������������������������������������������������������������������������������������������������������155 Status Codes�����������������������������������������������������������������������������������������������������������������������������156 x www.it-ebooks.info ■ Contents Caching and Validation��������������������������������������������������������������������������������������������������������������158 Content Encoding����������������������������������������������������������������������������������������������������������������������161 Content Negotiation�������������������������������������������������������������������������������������������������������������������161 Content Type������������������������������������������������������������������������������������������������������������������������������163 HTTP Authentication������������������������������������������������������������������������������������������������������������������163 Cookies��������������������������������������������������������������������������������������������������������������������������������������165 Connections, Keep-Alive, and httplib�����������������������������������������������������������������������������������������166 Summary�����������������������������������������������������������������������������������������������������������������������������������167 ■■Chapter 10: HTTP Servers����������������������������������������������������������������������������������������������169 WSGI������������������������������������������������������������������������������������������������������������������������������������������169 Asynchronous Server-Frameworks�������������������������������������������������������������������������������������������171 Forward and Reverse Proxies���������������������������������������������������������������������������������������������������171 Four Architectures���������������������������������������������������������������������������������������������������������������������172 Running Python Under Apache�������������������������������������������������������������������������������������������������������������������������� 174 The Rise of Pure-Python HTTP Servers������������������������������������������������������������������������������������������������������������� 174 The Benefits of Reverse Proxies������������������������������������������������������������������������������������������������������������������������ 174 Platforms as a Service��������������������������������������������������������������������������������������������������������������175 GET and POST Patterns and the Question of REST��������������������������������������������������������������������176 WSGI Without a Framework�������������������������������������������������������������������������������������������������������178 Summary�����������������������������������������������������������������������������������������������������������������������������������182 ■■Chapter 11: The World Wide Web����������������������������������������������������������������������������������183 Hypermedia and URLs���������������������������������������������������������������������������������������������������������������183 Parsing and Building URLs�������������������������������������������������������������������������������������������������������������������������������� 184 Relative URLs����������������������������������������������������������������������������������������������������������������������������������������������������� 186 The Hypertext Markup Language����������������������������������������������������������������������������������������������188 Reading and Writing to a Database�������������������������������������������������������������������������������������������191 A Terrible Web Application (in Flask)�����������������������������������������������������������������������������������������192 xi www.it-ebooks.info ■ Contents The Dance of Forms and HTTP Methods�����������������������������������������������������������������������������������197 When Forms Use Wrong Methods��������������������������������������������������������������������������������������������������������������������� 199 Safe and Unsafe Cookies����������������������������������������������������������������������������������������������������������������������������������� 199 Nonpersistent Cross-Site Scripting������������������������������������������������������������������������������������������������������������������� 201 Persistent Cross-Site Scripting�������������������������������������������������������������������������������������������������������������������������� 203 Cross-Site Request Forgery������������������������������������������������������������������������������������������������������������������������������� 203 The Improved Application���������������������������������������������������������������������������������������������������������������������������������� 204 The Payments Application in Django�����������������������������������������������������������������������������������������206 Choosing a Web Framework������������������������������������������������������������������������������������������������������210 WebSockets�������������������������������������������������������������������������������������������������������������������������������211 Web Scraping����������������������������������������������������������������������������������������������������������������������������212 Fetching Pages�������������������������������������������������������������������������������������������������������������������������������������������������� 213 Scraping Pages�������������������������������������������������������������������������������������������������������������������������������������������������� 216 Recursive Scraping�������������������������������������������������������������������������������������������������������������������������������������������� 218 Summary�����������������������������������������������������������������������������������������������������������������������������������222 ■■Chapter 12: Building and Parsing E-Mail����������������������������������������������������������������������223 E-Mail Message Format������������������������������������������������������������������������������������������������������������223 Building an E-Mail Message������������������������������������������������������������������������������������������������������225 Adding HTML and Multimedia���������������������������������������������������������������������������������������������������227 Adding Content��������������������������������������������������������������������������������������������������������������������������232 Parsing E-Mail Messages����������������������������������������������������������������������������������������������������������233 Walking MIME Parts������������������������������������������������������������������������������������������������������������������235 Header Encodings���������������������������������������������������������������������������������������������������������������������237 Parsing Dates����������������������������������������������������������������������������������������������������������������������������239 Summary�����������������������������������������������������������������������������������������������������������������������������������239 ■■Chapter 13: SMTP����������������������������������������������������������������������������������������������������������241 E-mail Clients vs Webmail Services�����������������������������������������������������������������������������������������241 In the Beginning Was the Command Line���������������������������������������������������������������������������������������������������������� 241 The Rise of Clients��������������������������������������������������������������������������������������������������������������������������������������������� 242 The Move to Webmail���������������������������������������������������������������������������������������������������������������������������������������� 243 xii www.it-ebooks.info ■ Contents How SMTP Is Used��������������������������������������������������������������������������������������������������������������������244 Sending E-Mail�������������������������������������������������������������������������������������������������������������������������������������������������� 246 Headers and the Envelope Recipient����������������������������������������������������������������������������������������������������������������� 246 Multiple Hops����������������������������������������������������������������������������������������������������������������������������������������������������� 247 Introducing the SMTP Library����������������������������������������������������������������������������������������������������248 Error Handling and Conversation Debugging����������������������������������������������������������������������������249 Getting Information from EHLO�������������������������������������������������������������������������������������������������252 Using Secure Sockets Layer and Transport Layer Security�������������������������������������������������������254 Authenticated SMTP������������������������������������������������������������������������������������������������������������������256 SMTP Tips����������������������������������������������������������������������������������������������������������������������������������258 Summary�����������������������������������������������������������������������������������������������������������������������������������258 ■■Chapter 14: POP������������������������������������������������������������������������������������������������������������259 POP Server Compatibility����������������������������������������������������������������������������������������������������������259 Connecting and Authenticating�������������������������������������������������������������������������������������������������260 Obtaining Mailbox Information��������������������������������������������������������������������������������������������������263 Downloading and Deleting Messages���������������������������������������������������������������������������������������264 Summary�����������������������������������������������������������������������������������������������������������������������������������266 ■■Chapter 15: IMAP�����������������������������������������������������������������������������������������������������������267 Understanding IMAP in Python��������������������������������������������������������������������������������������������������268 IMAPClient��������������������������������������������������������������������������������������������������������������������������������������������������������� 270 Examining Folders��������������������������������������������������������������������������������������������������������������������������������������������� 272 Message Numbers vs UIDs������������������������������������������������������������������������������������������������������������������������������� 273 Message Ranges����������������������������������������������������������������������������������������������������������������������������������������������� 273 Summary Information���������������������������������������������������������������������������������������������������������������������������������������� 274 Downloading an Entire Mailbox������������������������������������������������������������������������������������������������������������������������� 275 Downloading Messages Individually����������������������������������������������������������������������������������������������������������������� 277 Flagging and Deleting Messages����������������������������������������������������������������������������������������������������������������������� 283 Deleting Messages�������������������������������������������������������������������������������������������������������������������������������������������� 283 xiii www.it-ebooks.info ■ Contents Searching���������������������������������������������������������������������������������������������������������������������������������������������������������� 284 Manipulating Folders and Messages����������������������������������������������������������������������������������������������������������������� 285 Asynchrony�������������������������������������������������������������������������������������������������������������������������������������������������������� 286 Summary�����������������������������������������������������������������������������������������������������������������������������������287 ■■Chapter 16: Telnet and SSH�������������������������������������������������������������������������������������������289 Command-Line Automation�������������������������������������������������������������������������������������������������������289 Command-Line Expansion and Quoting������������������������������������������������������������������������������������������������������������ 290 Unix Command Arguments Can Include (Almost) Any Character����������������������������������������������������������������������� 291 Quoting Characters for Protection��������������������������������������������������������������������������������������������������������������������� 294 The Terrible Windows Command Line���������������������������������������������������������������������������������������������������������������� 295 Things Are Different in a Terminal��������������������������������������������������������������������������������������������������������������������� 295 Terminals Do Buffering�������������������������������������������������������������������������������������������������������������������������������������� 298 Telnet�����������������������������������������������������������������������������������������������������������������������������������������299 SSH: The Secure Shell���������������������������������������������������������������������������������������������������������������303 An Overview of SSH������������������������������������������������������������������������������������������������������������������������������������������� 304 SSH Host Keys��������������������������������������������������������������������������������������������������������������������������������������������������� 304 SSH Authentication�������������������������������������������������������������������������������������������������������������������������������������������� 306 Shell Sessions and Individual Commands��������������������������������������������������������������������������������������������������������� 307 SFTP: File Transfer Over SSH����������������������������������������������������������������������������������������������������������������������������� 312 Other Features��������������������������������������������������������������������������������������������������������������������������������������������������� 314 Summary�����������������������������������������������������������������������������������������������������������������������������������315 ■■Chapter 17: FTP�������������������������������������������������������������������������������������������������������������317 What to Use Instead of FTP�������������������������������������������������������������������������������������������������������317 Communication Channels���������������������������������������������������������������������������������������������������������������������������������� 318 Using FTP in Python������������������������������������������������������������������������������������������������������������������������������������������� 319 ASCII and Binary Files��������������������������������������������������������������������������������������������������������������������������������������� 320 Advanced Binary Downloading�������������������������������������������������������������������������������������������������������������������������� 321 Uploading Data�������������������������������������������������������������������������������������������������������������������������������������������������� 323 Advanced Binary Uploading������������������������������������������������������������������������������������������������������������������������������� 324 Handling Errors�������������������������������������������������������������������������������������������������������������������������������������������������� 325 xiv www.it-ebooks.info ■ Contents Scanning Directories����������������������������������������������������������������������������������������������������������������������������������������� 326 Detecting Directories and Recursive Download������������������������������������������������������������������������������������������������ 328 Creating Directories, Deleting Things���������������������������������������������������������������������������������������������������������������� 329 Doing FTP Securely�������������������������������������������������������������������������������������������������������������������������������������������� 330 Summary�����������������������������������������������������������������������������������������������������������������������������������330 ■■Chapter 18: RPC�������������������������������������������������������������������������������������������������������������331 Features of RPC�������������������������������������������������������������������������������������������������������������������������332 XML-RPC������������������������������������������������������������������������������������������������������������������������������������������������������������ 333 JSON-RPC���������������������������������������������������������������������������������������������������������������������������������������������������������� 339 Self-Documenting Data������������������������������������������������������������������������������������������������������������������������������������� 342 Talking About Objects: Pyro and RPyC��������������������������������������������������������������������������������������������������������������� 343 An RPyC Example���������������������������������������������������������������������������������������������������������������������������������������������� 344 RPC, Web Frameworks, and Message Queues�������������������������������������������������������������������������������������������������� 346 Recovering from Network Errors����������������������������������������������������������������������������������������������������������������������� 346 Summary�����������������������������������������������������������������������������������������������������������������������������������347 Index���������������������������������������������������������������������������������������������������������������������������������349 xv www.it-ebooks.info About the Authors Brandon Rhodes is a consulting programmer who also teaches the Python language professionally for organizations that are adding the language to their tool set He has spoken at PyOhio; at PyGotham; at national PyCon conferences in Canada, Ireland, and Poland; and at Django conferences in Portland, Wales, and Warsaw, where he was delighted at the creativity of the organizers, who rented a circus tent for the occasion He will chair the flagship PyCon North America conference in Portland in 2016–2017 Brandon is interested in how ideas like the Clean Architecture can help programmers organize code more effectively and in what we can learn from writers in other fields about offering kind and actionable critiques of each other’s work He currently lives in tiny Bluffton, Ohio, with his wife Jackie and their two cats John Goerzen is an accomplished author, system administrator, and Python programmer He has been a Debian developer since 1996 and is currently president of Software in the Public Interest, Inc His previously published books include the Linux Programming Bible, Debian Unleashed, and Linux Unleashed xvii www.it-ebooks.info About the Technical Reviewers Originally from Canada’s great north, Alexandre Beaulne pursued a bachelor’s degree in systems neuroscience at McGill University in Montreal, followed by a master’s degree in financial engineering at HEC Montreal His studies, however, culminated in his attendance at Hacker School in New York City He has repeatedly made the unsupported claim that he “gets” Haskell’s monads Peter Membrey is a Chartered IT Fellow with over 15 years of experience using Linux and Open Source solutions to solve problems in the real world An RHCE since the age of 17, he has also had the honour of working for Red Hat and writing several books covering open source solutions He holds a Masters degree in IT (Information Security) from the University of Liverpool, and he is currently a PhD candidate at the Hong Kong Polytechnic University, where his research interests include cloud computing, big data science, and security He lives in Hong Kong with his wonderful wife Sarah and their son Kaydyn His Cantonese continues to regress, though his Esperanto is coming along nicely xix www.it-ebooks.info Acknowledgments Five years ago, as I was revising and rewriting to prepare a second edition of this book, I was deeply impressed by how much had changed in the half-decade since its debut in 2004 New web frameworks like CherryPy and Django were creating a revolution in how programmers wrote for the Web, while libraries such as mechanize and lxml were making it easier than ever to fetch information from HTTP servers As I wrap up this third edition, it is clear that the Python community has done it again! Improvements large and small have required changes to the text and, in some cases, a complete rewrite of entire chapters From the core developers who produced the new Python version of the language, to the authors of new web frameworks such as Flask and Tornado who continue to make the task of writing HTTP services both more convenient and much safer, to the programmers who maintain modules both inside and outside of the Standard Library, this new edition is first and foremost a reflection of the hard work that an entire programming language community—really, an entire ecosystem—has poured into the tools and libraries that help us write programs for the Internet A number of readers have contacted me since the second edition came out with questions, with ideas, or to point out where a program listing now failed or was no longer valid I hope they know that their feedback was important to the process of creating this new edition, and I think a few of them will recognize where their ideas have wound up making noticeable improvements to the book Many thanks to the editors and reviewers at Apress who read my (at some moments, appalling) first drafts, who caught bugs and outright errors in my program listings, and who helped shepherd this rewrite through to completion I want to give particular credit to the copy editors, through whom I have slowly learned not to say the word very or actually in every other sentence and thanks to whom I continue to make progress in my lifelong journey toward being able to tell when to use that and when to use which when connecting clauses Thanks, finally, to everyone who had to wait on an e-mail, bug fix, or meeting as I have been writing, and especially to my wife Jackie for all of her encouragement xxi www.it-ebooks.info ... DNS����������������������������������������������������������������������������������57 ■■Chapter 5: Network Data and Network Errors�����������������������������������������������������������������75 ■■Chapter 6: TLS/SSL����������������������������������������������������������������������������������������������������������93... their new names, or debug deeply flawed network code that relied on Python 2’s dangerous automatic conversion between byte strings and Unicode strings—conversions that were always based on rough... on network programming, using Python for every example script and snippet of code at the Python prompt These examples are intended to build a comprehensive picture of how network clients, network

Ngày đăng: 27/03/2017, 11:47

Từ khóa liên quan

Mục lục

  • Contents at a Glance

  • Contents

  • About the Author

  • About the Technical Reviewers

  • Acknowledgments

  • Introduction

  • Chapter 1: Introduction to Client-Server Networking

    • The Building Blocks: Stacks and Libraries

    • Application Layers

    • Speaking a Protocol

    • A Raw Network Conversation

    • Turtles All the Way Down

    • Encoding and Decoding

    • The Internet Protocol

    • IP Addresses

    • Routing

    • Packet Fragmentation

    • Learning More About IP

    • Summary

    • Chapter 2: UDP

      • Port Numbers

      • Sockets

        • Promiscuous Clients and Unwelcome Replies

Tài liệu cùng người dùng

Tài liệu liên quan