100% found this document useful (1 vote)
29 views

Python Penetration Testing Essentials Techniques for ethical hacking with Python 2nd Edition Mohit - Download the ebook and start exploring right away

The document promotes various eBooks available for download at ebookmeta.com, including 'Python Penetration Testing Essentials' by Mohit, which focuses on ethical hacking techniques using Python. It also lists additional recommended titles related to ethical hacking and security testing. The document provides links for instant downloads and mentions the author's background and the book's content structure.

Uploaded by

oedinxynab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
29 views

Python Penetration Testing Essentials Techniques for ethical hacking with Python 2nd Edition Mohit - Download the ebook and start exploring right away

The document promotes various eBooks available for download at ebookmeta.com, including 'Python Penetration Testing Essentials' by Mohit, which focuses on ethical hacking techniques using Python. It also lists additional recommended titles related to ethical hacking and security testing. The document provides links for instant downloads and mentions the author's background and the book's content structure.

Uploaded by

oedinxynab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

Python Penetration Testing Essentials Techniques


for ethical hacking with Python 2nd Edition Mohit

https://ebookmeta.com/product/python-penetration-testing-
essentials-techniques-for-ethical-hacking-with-python-2nd-
edition-mohit/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Beginning Ethical Hacking with Python 1st Edition Sanjib


Sinha

https://ebookmeta.com/product/beginning-ethical-hacking-with-
python-1st-edition-sanjib-sinha/

ebookmeta.com

Learning Kali Linux Security Testing Penetration Testing


and Ethical Hacking 1st Edition Ric Messier

https://ebookmeta.com/product/learning-kali-linux-security-testing-
penetration-testing-and-ethical-hacking-1st-edition-ric-messier/

ebookmeta.com

Learning Kali Linux: Security Testing, Penetration


Testing, and Ethical Hacking, 2nd Edition - First Early
Release Ric Messier
https://ebookmeta.com/product/learning-kali-linux-security-testing-
penetration-testing-and-ethical-hacking-2nd-edition-first-early-
release-ric-messier/
ebookmeta.com

Mayor of Elf Town 4 1st Edition Dante King

https://ebookmeta.com/product/mayor-of-elf-town-4-1st-edition-dante-
king-2/

ebookmeta.com
Theatre Translation: A Practice as Research Model 1st
Edition Angela Tiziana Tarantini

https://ebookmeta.com/product/theatre-translation-a-practice-as-
research-model-1st-edition-angela-tiziana-tarantini/

ebookmeta.com

Essential Revision Notes for FRCS Urol Book 1 1st Edition


Jack Donati Bourne

https://ebookmeta.com/product/essential-revision-notes-for-frcs-urol-
book-1-1st-edition-jack-donati-bourne/

ebookmeta.com

Eyewitness to Chaos Personal Accounts of the Intervention


in Haiti 1994 1st Edition Walter E Kretchik

https://ebookmeta.com/product/eyewitness-to-chaos-personal-accounts-
of-the-intervention-in-haiti-1994-1st-edition-walter-e-kretchik/

ebookmeta.com

The Blobfish Book Jessica Olien

https://ebookmeta.com/product/the-blobfish-book-jessica-olien/

ebookmeta.com

Spoon Feeding Basic must Know Physics for Boys and Men for
IIT JEE Olympiad kind of exams by Professor Subhashish
Chattopadhyay 1st Edition Professor Subhashish
Chattopadhyay
https://ebookmeta.com/product/spoon-feeding-basic-must-know-physics-
for-boys-and-men-for-iit-jee-olympiad-kind-of-exams-by-professor-
subhashish-chattopadhyay-1st-edition-professor-subhashish-
chattopadhyay/
ebookmeta.com
College Reunions and Clues Tiffany Black Travel Cozy
Mystery 4 A.R. Winters Et El

https://ebookmeta.com/product/college-reunions-and-clues-tiffany-
black-travel-cozy-mystery-4-a-r-winters-et-el/

ebookmeta.com
||||||||||||||||||||

||||||||||||||||||||
||||||||||||||||||||

Python Penetration Testing


Essentials
Second Edition

5FDIOJRVFTGPSFUIJDBMIBDLJOHXJUI1ZUIPO

Mohit

BIRMINGHAM - MUMBAI

||||||||||||||||||||
||||||||||||||||||||

Python Penetration Testing Essentials


Second Edition
Copyright a 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, without the prior written permission of the publisher, except in the case of brief quotations
embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to
have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy
of this information.

Commissioning Editor: Vijin Boricha


Acquisition Editor: Noyonika Das
Content Development Editor: Roshan Kumar
Technical Editor: Sushmeeta Jena
Copy Editor: Safis Editing
Project Coordinator: Hardik Bhinde
Proofreader: Safis Editing
Indexer: Aishwarya Gangawane
Graphics: Jason Monteiro
Production Coordinator: Deepika Naik

First published: January 2015


Second edition: May 2018

Production reference: 1290518

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78913-896-2

XXXQBDLUQVCDPN

||||||||||||||||||||
||||||||||||||||||||

NBQUJP

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.

Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at XXX1BDLU1VCDPN and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at TFSWJDF!QBDLUQVCDPN for more details.

At XXX1BDLU1VCDPN, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.

||||||||||||||||||||
||||||||||||||||||||

Contributors

About the author


Mohit is a Python programmer with a keen interest in the field of information security. He
has B.Tech (UIET, KUK, 2009) and M.E (Thapar University, 2012) degree. He is a CEH,
ECSA at EC-Council USA. He has worked in IBM and Sapient. He is currently doing PhD
from Thapar Institute of Engg & Technology under Dr. Maninder Singh. He has published
several articles in national and international magazines. He is the author of Python
Penetration Testing Essentials, Python: Penetration Testing for Developers and Learn Python in 7
Days also by Packt. His username is mohitrajcs on gmail. .

||||||||||||||||||||
||||||||||||||||||||

About the reviewers


Sanjeev Jaiswal is a computer graduate from CUSAT with 9 years of industrial experience.
He uses Perl, Python, AWS, and GNU/Linux for his day-to-day activities. He's currently
working on projects involving penetration testing, source code review, security design, and
implementations in AWS and Cloud security projects.

He is learning DevSecOps and security automation currently as well. Sanjeev loves


teaching engineering students and IT professionals. He has been teaching for the past 8
years in his leisure time. He founded Alien Coders and Cybercloud Guru as well.

My special thanks to my wife, Shalini Jaiswal, for her unconditional support, and my
friends Ranjan, Ritesh, Mickey, Vivek, Hari, Sujay, Shankar, and Santosh for their care
and support all the time.

Rejah Rehim is currently the Director and Chief Information Security Officer (CISO) of
Appfabs. Previously holding the title of Security Architect at FAYA India, he is a long-time
preacher of open source and steady contributor to the Mozilla Foundation. He has
successfully created the world's first security testing browser bundle, PenQ, an open
source Linux-based penetration testing browser bundle preconfigured with tools
for security testing. He is also an active member of OWASP and the chapter
leader of OWASP Kerala. Additionally, Rejah also holds the title of commander at
Cyberdome, an initiative of the Kerala Police Department.

Packt is searching for authors like you


If you're interested in becoming an author for Packt, please visit BVUIPSTQBDLUQVCDPN
and apply today. We have worked with thousands of developers and tech professionals,
just like you, to help them share their insight with the global tech community. You can
make a general application, apply for a specific hot topic that we are recruiting an author
for, or submit your own idea.

||||||||||||||||||||
||||||||||||||||||||

Table of Contents
Preface 1
Chapter 1: Python with Penetration Testing and Networking 6
Introducing the scope of pentesting 7
The need for pentesting 7
Components to be tested 8
Qualities of a good pentester 8
Defining the scope of pentesting 9
Approaches to pentesting 9
Introducing Python scripting 10
Understanding the tests and tools you'll need 11
Learning the common testing platforms with Python 11
Network sockets 11
Server socket methods 12
Client socket methods 13
General socket methods 13
Moving on to the practical 14
Socket exceptions 22
Useful socket methods 23
Summary 29
Chapter 2: Scanning Pentesting 30
How to check live systems in a network and the concept of a live
system 31
Ping sweep 31
The TCP scan concept and its implementation using a Python script 35
How to create an efficient IP scanner in Windows 37
How to create an efficient IP scanner in Linux 44
The concept of the Linux-based IP scanner 44
nmap with Python 47
What are the services running on the target machine? 51
The concept of a port scanner 51
How to create an efficient port scanner 54
Summary 59
Chapter 3: Sniffing and Penetration Testing 60
Introducing a network sniffer 61
Passive sniffing 61
Active sniffing 61
Implementing a network sniffer using Python 61

||||||||||||||||||||
||||||||||||||||||||

Table of Contents

Format characters 63
Learning about packet crafting 73
Introducing ARP spoofing and implementing it using Python 74
The ARP request 74
The ARP reply 75
The ARP cache 75
Testing the security system using custom packet crafting 78
A half-open scan 79
The FIN scan 82
ACK flag scanning 83
Summary 85
Chapter 4: Network Attacks and Prevention 86
Technical requirements 86
DHCP starvation attack 87
The MAC flooding attack 93
How the switch uses the CAM tables 93
The MAC flood logic 94
Gateway disassociation by RAW socket 95
Torrent detection 96
Running the program in hidden mode 104
Summary 106
Chapter 5: Wireless Pentesting 107
Introduction to 802.11 frames 108
Wireless SSID finding and wireless traffic analysis with Python 110
Detecting clients of an AP 120
Wireless hidden SSID scanner 122
Wireless attacks 125
The deauthentication (deauth) attack 125
Detecting the deauth attack 128
Summary 131
Chapter 6: Honeypot – Building Traps for Attackers 132
Technical requirements 132
Fake ARP reply 133
Fake ping reply 135
Fake port-scanning reply 142
Fake OS-signature reply to nmap 145
Fake web server reply 146
Summary 149
Chapter 7: Foot Printing a Web Server and a Web Application 150
The concept of foot printing a web server 150
Introducing information gathering 151

[ ii ]

||||||||||||||||||||
||||||||||||||||||||

Table of Contents

Checking the HTTP header 155


Information gathering of a website from whois.domaintools.com 157
Email address gathering from a web page 159
Banner grabbing of a website 160
Hardening of a web server 161
Summary 162
Chapter 8: Client-Side and DDoS Attacks 163
Introducing client-side validation 163
Tampering with the client-side parameter with Python 164
Effects of parameter tampering on business 169
Introducing DoS and DDoS 172
Single IP, single ports 172
Single IP, multiple port 174
Multiple IP, multiple ports 176
Detection of DDoS 178
Summary 181
Chapter 9: Pentesting SQL and XSS 182
Introducing the SQL injection attack 183
Types of SQL injections 184
Simple SQL injection 184
Blind SQL injection 184
Understanding the SQL injection attack by a Python script 184
Learning about cross-site scripting 194
Persistent or stored XSS 195
Nonpersistent or reflected XSS 195
Summary 204
Other Books You May Enjoy 205
Index 208

[ iii ]

||||||||||||||||||||
||||||||||||||||||||

Preface
This book is a practical guide that shows you the advantages of using Python for
pentesting, with the help of detailed code examples. This book starts by exploring the
basics of networking with Python and then proceeds to network and wireless pentesting,
including information gathering and attacking. You will learn how to build honeypot traps.
Later on, we delve into hacking the application layer, where we start by gathering
information from a website, and then eventually move on to concepts related to website
hacking, such as parameter tampering, DDOS, XSS, and SQL injection.

Who this book is for


If you are a Python programmer, a security researcher, or a network admin who has basic
knowledge of Python programming and want to learn about penetration testing with the
help of Python, this book is ideal for you. Even if you are new to the field of ethical hacking,
this book can help you find the vulnerabilities in your system so that you are ready to
tackle any kind of attack or intrusion.

What this book covers


$IBQUFS, Python with Penetration Testing and Networking, goes through the prerequisites of
the following chapters. This chapter also discusses the socket and its methods. The server
socket's method defines how to create a simple server.

$IBQUFS, Scanning Pentesting, covers how to perform network scanning to gather


information on a network, host, and the services that are running on the hosts. You will see
a very fast and efficient IP scanner.

$IBQUFS, Sniffing and Penetration Testing, teaches how to perform active sniffing and how
to create a Transport layer sniffer. You will learn special kinds of scanning.

$IBQUFS, Network Attacks and Prevention, outlines different types of network attacks, such
as DHCP starvation and switch mac flooding. You will learn how to detect a torrent on the
client side.

||||||||||||||||||||
||||||||||||||||||||

Preface

$IBQUFS, Wireless Pentesting, goes through wireless frames and explains how to obtain
information such as SSID, BSSID, and the channel number from a wireless frame using a
Python script. In this type of attack, you will learn how to perform pentesting attacks on the
AP.

$IBQUFS, Honeypot ` Building Traps for Attackers, focuses on how to build a trap for
attackers. You will learn how to bulid code from TCP layer 2 to TCP layer 4.

$IBQUFS, Foot Printing a Web Server and a Web Application, dives into the importance of a
web server signature, email gathering, and why knowing the server signature is the first
step in hacking.

$IBQUFS, Client-Side and DDoS Attacks, explores client-side validation and how to bypass
client-side validation. This chapter covers the implantation of four types of DDoS attacks.

$IBQUFS, Pentesting SQL and XSS, discusses two major web attacks: SQL injection and
XSS. In SQL injection, you will learn how to find the admin login page using a Python
script.

To get the most out of this book


In order to understand the book reader must have the knowledge of Networking
fundamentals, basic knowledge of Linux OS, good knowledge of information security and
core Python.

In order to perform experiments or run the codes reader can use the virtual machine
(Vmware, virtual box). For Wireless pen-testing readers can use a wireless card TP-Link TL-
WN722N. Becuase TL-WN722N wireless card supports the Kali Linux in VMware.

Download the example code files


You can download the example code files for this book from your account at
XXXQBDLUQVCDPN. If you purchased this book elsewhere, you can visit
XXXQBDLUQVCDPNTVQQPSU and register to have the files emailed directly to you.

[2]

||||||||||||||||||||
||||||||||||||||||||

Preface

You can download the code files by following these steps:

1. Log in or register at XXXQBDLUQVCDPN.


2. Select the SUPPORT tab.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box and follow the onscreen
instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR/7-Zip for Windows


Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at IUUQTHJUIVCDPN
1BDLU1VCMJTIJOH1ZUIPO1FOFUSBUJPO5FTUJOH&TTFOUJBMT4FDPOE&EJUJPO. In case
there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available
at IUUQTHJUIVCDPN1BDLU1VCMJTIJOH. Check them out!

Download the color images


We also provide a PDF file that has color images of the screenshots/diagrams used in this
book. You can download it here: IUUQXXXQBDLUQVCDPNTJUFTEFGBVMUGJMFT
EPXOMPBET1ZUIPO1FOFUSBUJPO5FTUJOH&TTFOUJBMT4FDPOE&EJUJPO@$PMPS*NBHFTQEG.

Code in Action
Visit the following link to check out videos of the code being run:
IUUQTHPPHMT#)7/%

[3]

||||||||||||||||||||
||||||||||||||||||||

Preface

Conventions used
There are a number of text conventions used throughout this book.

$PEF*O5FYU: Indicates code words in text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an
example: "Mount the downloaded 8FC4UPSN ENH disk image file as another disk in
your system."

A block of code is set as follows:


JNQPSUPT
SFTQPOTFPTQPQFO QJOHO
GPSMJOFJOSFTQPOTFSFBEMJOFT 
QSJOUMJOF

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,TPDLFUOUPIT Y
J

Any command-line input or output is written as follows:


python setup.py install

Bold: Indicates a new term, an important word, or words that you see onscreen. For
example, words in menus or dialog boxes appear in the text like this. Here is an example:
"Select System info from the Administration panel."

Warnings or important notes appear like this.

Tips and tricks appear like this.

[4]

||||||||||||||||||||
||||||||||||||||||||

Preface

Get in touch
Feedback from our readers is always welcome.

General feedback: Email GFFECBDL!QBDLUQVCDPN and mention the book title in the
subject of your message. If you have questions about any aspect of this book, please email
us at RVFTUJPOT!QBDLUQVCDPN.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book, we would be grateful if you would
report this to us. Please visit XXXQBDLUQVCDPNTVCNJUFSSBUB, selecting your book,
clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we
would be grateful if you would provide us with the location address or website name.
Please contact us at DPQZSJHIU!QBDLUQVCDPN with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in
and you are interested in either writing or contributing to a book, please visit
BVUIPSTQBDLUQVCDPN.

Reviews
Please leave a review. Once you have read and used this book, why not leave a review on
the site that you purchased it from? Potential readers can then see and use your unbiased
opinion to make purchase decisions, we at Packt can understand what you think about our
products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit QBDLUQVCDPN.

[5]

||||||||||||||||||||
||||||||||||||||||||

1
Python with Penetration Testing
and Networking
Penetration (pen) tester and hacker are similar terms. The difference is that penetration
testers work for an organization to prevent hacking attempts, while hackers hack for any
purpose such as fame, selling vulnerability for money, or to exploit the vulnerability of
personal enmity.

Lots of well-trained hackers have got jobs in the information security field by hacking into a
system and then informing the victim of their security bug(s) so that they might be fixed.

A hacker is called a penetration tester when they work for an organization or company to
secure its system. A pentester performs hacking attempts to break into the network after
getting legal approval from the client and then presents a report of their findings. To
become an expert in pentesting, a person should have a deep knowledge of the concepts of
their technology. In this chapter, we will cover the following topics:

The scope of pentesting


The need for pentesting
Components to be tested
Qualities of a good pentester
Approaches to pentesting
Understanding the tests and tools you'll need
Network sockets
Server socket methods
Client socket methods
General socket methods
Practical examples of sockets
Socket exceptions
Useful socket methods

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Introducing the scope of pentesting


In simple words, penetration testing is used to test the information security measures of a
company. Information security measures entail a company's network, database, website,
public-facing servers, security policies, and everything else specified by the client. At the
end of the day, a pentester must present a detailed report of their findings such as
weaknesses, vulnerabilities in the company's infrastructure, and the risk level of particular
vulnerabilities, and provide solutions if possible.

The need for pentesting


There are several points that describe the significance of pentesting:

Pentesting identifies the threats that might expose the confidentiality of an


organization
Expert pentesting provides assurance to the organization with a complete and
detailed assessment of organizational security
Pentesting assesses the network's efficiency by producing a huge amount of
traffic and scrutinizes the security of devices such as firewalls, routers, and
switches
Changing or upgrading the existing infrastructure of software, hardware, or
network design might lead to vulnerabilities that can be detected by pentesting
In today's world, potential threats are increasing significantly; pentesting is a
proactive exercise to minimize the chances of being exploited
Pentesting ensures whether suitable security policies are being followed or not

Consider the example of a well-reputed e-commerce company that makes money from an
online business. A hacker or a group of black hat hackers find a vulnerability in the
company's website and hack it. The amount of loss the company will have to bear will be
tremendous.

[7]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Components to be tested
An organization should conduct a risk assessment operation before pentesting; this will
help identify the main threats such as misconfiguration or vulnerability in:

Routers, switches, or gateways


Public-facing systems; websites, DMZ, email servers, and remote systems
DNS, firewalls, proxy servers, FTP, and web servers

Testing should be performed on all hardware and software components of a network


security system.

Qualities of a good pentester


The following points describe the qualities of a good pentester. They should:

Choose a suitable set of tests and tools that balance cost and benefits
Follow suitable procedures with proper planning and documentation
Establish the scope for each penetration test, such as objectives, limitations, and
the justification of procedures
Be ready to show how to exploit the vulnerabilities that they find
State the potential risks and findings clearly in the final report and provide
methods to mitigate the risk(s) if possible
Keep themselves updated at all times because technology is advancing rapidly

A pentester tests the network using manual techniques or the relevant tools. There are lots
of tools available on the market. Some of them are open source and some of them are highly
expensive. With the help of programming, a programmer can make his/her own tools. By
creating your own tools, you can clear your concepts and also perform more R&D. If you
are interested in pentesting and want to make your own tools, then the Python
programming language is the best, since extensive and freely available pentesting packages
are available in Python, in addition to its ease of programming. This simplicity, along with
the third-party libraries such as scapy and mechanize, reduces the code size. In Python, to
make a program, you don't need to define big classes such as Java. It's more productive to
write code in Python than in C, and high-level libraries are easily available for virtually any
imaginable task.

If you know some programming in Python and are interested in pentesting, this book is
perfect for you.

[8]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Defining the scope of pentesting


Before we get into pentesting, the scope of pentesting should be defined. The following
points should be taken into account while defining the scope:

You should develop the scope of the project by consulting with the client. For
example, if Bob (the client) wants to test the entire network infrastructure of the
organization, then pentester Alice would define the scope of pentesting by taking
this network into account. Alice will consult Bob on whether any sensitive or
restricted areas should be included or not.
You should take into account time, people, and money.
You should profile the test boundaries on the basis of an agreement signed by the
pentester and the client.
Changes in business practice might affect the scope. For example, the addition of
a subnet, new system component installations, the addition or modification of a
web server, and so on, might change the scope of pentesting.

The scope of pentesting is defined in two types of tests:

A non-destructive test: This test is limited to finding and carrying out the tests
without any potential risks. It performs the following actions:
Scans and identifies the remote system for potential vulnerabilities
Investigates and verifies the findings
Maps the vulnerabilities with proper exploits
Exploits the remote system with proper care to avoid disruption
Provides a proof of concept
Does not attempt a Denial-of-Service (DoS) attack
A destructive test: This test can produce risks. It performs the following actions:
Attempts a DoS attack and a buffer overflow attack, which have
the potential to bring down the system

Approaches to pentesting
There are three types of approaches to pentesting:

Black-box pentesting follows a non-deterministic approach of testing:


You will be given just a company name
It is like hacking with the knowledge of an outside attacker

[9]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

You do not need any prior knowledge of the system


It is time-consuming
White-box pentesting follows a deterministic approach to testing:
You will be given complete knowledge of the infrastructure that
needs to be tested
This is like working as a malicious employee who has ample
knowledge of the company's infrastructure
You will be provided information on the company's infrastructure,
network type, company's policies, do's and don'ts, the IP address,
and the IPS/IDS firewall
Gray-box pentesting follows a hybrid approach of black-box and white-box
testing:
The tester usually has limited information on the target
network/system that is provided by the client to lower the costs
and decrease trial and error on the part of the pentester
It performs the security assessment and testing internally

Introducing Python scripting


Before you start reading this book, you should know the basics of Python programming,
such as the basic syntax, variable type, data type tuple, list dictionary, functions, strings,
and methods. Two versions, 3.4 and 2.7.8, are available at QZUIPOPSHEPXOMPBET.

In this book, all experiments and demonstrations have been done in Python version 2.7.8. If
you use Linux OSes such as Kali or BackTrack, then there will be no issue, because many
programs, such as wireless sniffing, do not work on the Windows platform. Kali Linux also
uses the 2.7 version. If you love to work on Red Hat or CentOS, then this version is suitable
for you.

Most hackers choose this profession because they don't want to do programming. They
want to use tools. However, without programming, a hacker cannot enhance his/her skills.
Each and every time, they have to search for the tools over the internet. Believe me, after
seeing its simplicity, you will love this language.

[ 10 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Understanding the tests and tools you'll


need
As you have seen, this book is divided into nine chapters. To conduct scanning and sniffing
pentesting, you will need a small network of attached devices. If you don't have a lab, you
can make virtual machines on your computer. For wireless traffic analysis, you should have
a wireless network. To conduct a web attack, you will need an Apache server running on
the Linux platform. It is a good idea to use CentOS or Red Hat Version 5 or 6 for the web
server because this contains the RPM of Apache and PHP. For the Python script, we will
use the Wireshark tool, which is open source and can be run on Windows as well as Linux
platforms.

Learning the common testing platforms with


Python
You will now perform some pentesting; I hope you are well acquainted with networking
fundamentals such as IP addresses, classful subnetting, classless subnetting, the meaning of
ports, network addresses, and broadcast addresses. A pentester must be knowledgeable in
networking fundamentals as well as in at least one operating system; if you are thinking of
using Linux, then you are on the right track. In this book, we will execute our programs on
Windows as well as Linux. In this book, Windows, CentOS, and Kali Linux will be used.

A hacker always loves to work on a Linux system. Since it is a free and open source, Kali
Linux marks the rebirth of BackTrack and is like an arsenal of hacking tools. Kali Linux
NetHunter is the first open-source Android penetration testing platform for Nexus devices.
However, some tools work on both Linux and Windows, but on Windows, you have to
install those tools. I expect you to have knowledge of Linux. Now, it's time to work with
networking on Python.

Network sockets
A network socket address contains an IP address and port number. In a very simple way, a
socket is a way to talk to other computers. By means of a socket, a process can communicate
with another process over the network.

[ 11 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

In order to create a socket, use the TPDLFUTPDLFU that is available in the socket
module. The general syntax of a socket function is as follows:
TTPDLFUTPDLFU TPDLFU@GBNJMZTPDLFU@UZQFQSPUPDPM

Here is the description of the parameters:


TPDLFU@GBNJMZTPDLFU"'@*/&51'@1"$,&5

"'@*/&5 is the address family for IPv4. 1'@1"$,&5 operates at the device driver layer. The
pcap library for Linux uses 1'@1"$,&5. You will see more details on 1'@1"$,&5 in
$IBQUFS, Sniffing and Penetration Testing. These arguments represent the address families
and the protocol of the transport layer:
4PDLFU@UZQFTPDLFU40$,@%(3".TPDLFU40$,@3"8TPDLFU40$,@453&".

The TPDLFU40$,@%(3". argument depicts that UDP is unreliable and connectionless, and
TPDLFU40$,@453&". depicts that TCP is reliable and a two-way, connection-based
service. We will discuss TPDLFU40$,@3"8 in $IBQUFS, Sniffing and Penetration Testing:
QSPUPDPM

Generally, we leave this argument; it takes 0 if it's not specified. We will see the use of this
argument in $IBQUFS, Sniffing and Penetration Testing.

Server socket methods


In a client-server architecture, there is one centralized server that provides service, and
many clients request and receive service from the centralized server. Here are some
methods you need to know:

TPDLFUCJOE BEESFTT : This method is used to connect the address (IP


address, port number) to the socket. The socket must be open before connecting
to the address.
TPDLFUMJTUFO R : This method starts the TCP listener. The R argument
defines the maximum number of lined-up connections.

[ 12 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

TPDLFUBDDFQU : The use of this method is to accept the connection from the
client. Before using this method, the TPDLFUCJOE BEESFTT and
TPDLFUMJTUFO R methods must be used. The TPDLFUBDDFQU method
returns two values, DMJFOU@TPDLFU and BEESFTT, where DMJFOU@TPDLFU is a
new socket object used to send and receive data over the connection, and
BEESFTT is the address of the client. You will see examples of this later.

Client socket methods


The only method dedicated to the client is the following:

TPDLFUDPOOFDU BEESFTT : This method connects the client to the server. The
BEESFTT argument is the address of the server.

General socket methods


The general socket methods are as follows:

TPDLFUSFDW CVGTJ[F : This method receives a TCP message from the socket.
The CVGTJ[F argument defines the maximum data it can receive at any one time.
TPDLFUSFDWGSPN CVGTJ[F : This method receives data from the socket. The
method returns a pair of values, the first value gives the received data, and the
second value gives the address of the socket sending the data.
TPDLFUSFDW@JOUP CVGGFS : This method receives data less than or equal to
CVGGFS. The CVGGFS parameter is created by the CZUFBSSBZ method. We will
discuss this in an example later.
TPDLFUSFDWGSPN@JOUP CVGGFS : This method obtains data from the socket
and writes it into the buffer. The return value is a pair (nbytes, address), where
nbytes is the number of bytes received, and the address is the address of the
socket sending the data.

Be careful while using the TPDLFUSFDWGSPN@JOUP CVGGFS method


in older versions of Python. Buffer overflow vulnerability has been found
in this method. The name of this vulnerability is CVE-2014-1912, and its
vulnerability was published on February 27, 2014. Buffer overflow in the
TPDLFUSFDWGSPN@JOUP function in .PEVMFTTPDLFUNPEVMFD in
Python 2.5 before 2.7.7, 3.x before 3.3.4, and 3.4.x before 3.4rc1, allows
remote attackers to execute arbitrary code via a crafted string.

[ 13 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

TPDLFUTFOE CZUFT : This method is used to send data to the socket. Before
sending the data, ensure that the socket is connected to a remote machine. It
returns the number of bytes sent.
TPDLFUTFOEUP EBUBBEESFTT : This method is used to send data to the
socket. Generally, we use this method in UDP. UDP is a connectionless protocol;
therefore, the socket should not be connected to a remote machine, and the
address argument specifies the address of the remote machine. The returned
value tells us the number of bytes sent.
TPDLFUTFOEBMM EBUB : As the name implies, this method sends all data to the
socket. Before sending the data, ensure that the socket is connected to a remote
machine. This method ceaselessly transfers data until an error is seen. If an error
is seen, an exception will rise, and TPDLFUDMPTF will close the socket.

Now, it is time for the practical; no more mundane theory.

Moving on to the practical


First, we will make a server-side program that offers a connection to the client and sends a
message to the client. Run TFSWFSQZ:
JNQPSUTPDLFU
IPTU4FSWFSBEESFTT
QPSU1PSUPG4FSWFS
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
TCJOE IPTUQPSU CJOETFSWFS
TMJTUFO 
DPOOBEESTBDDFQU
QSJOUBEES/PX$POOFDUFE
DPOOTFOE 5IBOLZPVGPSDPOOFDUJOH
DPOODMPTF

The preceding code is very simple; it is minimal code on the server side.

[ 14 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

First, import the socket module and define the host and port number,  is the
server's IP address. 4PDLFU"'@*/&5 defines the IPv4 protocol's family.
4PDLFU40$,@453&". defines the TCP connection. The TCJOE IPTUQPSU statement
takes only one argument. It binds the socket to the host and port number. The
TMJTUFO  statement listens to the connection and waits for the client. The DPOOBEES
TBDDFQU statement returns two values: DPOO and BEES. The DPOO socket is the client
socket, as we discussed earlier. The DPOOTFOE function sends the message to the client.
Finally, DPOODMPTF closes the socket. From the following examples and screenshot, you
will understand DPOO better.

This is the output of the TFSWFSQZ program:


G:PythonNetworking>python server1.py

Now, the server is in the listening mode and is waiting for the client.

Let's see the client-side code. Run DMJFOUQZ:


JNQPSUTPDLFU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
IPTUTFSWFSBEESFTT
QPSUTFSWFSQPSU
TDPOOFDU IPTUQPSU
QSJOUTSFDW 
TTFOE )FMMP4FSWFS
TDMPTF

In the preceding code, there are two new methods, TDPOOFDU IPTUQPSU , which
connects the client to the server, and TSFDW  , which receives the strings sent by the
server.

The output of DMJFOUQZ and the response of the server is shown in the following
screenshot:

[ 15 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

The preceding screenshot of the output shows that the server accepted the connection from
. Don't get confused by seeing port ; it is the random port of the client.
When the server sends a message to the client, it uses the DPOO socket, as mentioned earlier,
and this DPOO socket contains the client IP address and port number.

The following diagram shows how the client accepts a connection from the server. The
server is in listening mode, and the client connects to the server. When you run the server
and client program again, the random port gets changed. For the client, the server
port, 12345, is the destination port, and for the server, the client random port, 1789, is the
destination port:

6%2EQOOWPKECVKQP

You can extend the functionality of the server using the XIJMF loop, as shown in the
following program. Run the TFSWFSQZ program:
JNQPSUTPDLFU

[ 16 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
TCJOE IPTUQPSU
TMJTUFO 
XIJMF5SVF
DPOOBEESTBDDFQU
QSJOUBEES/PX$POOFDUFE
DPOOTFOE 5IBOLZPVGPSDPOOFDUJOH
DPOODMPTF

The preceding code is the same as the previous one, except the infinite XIJMF loop has been
added.

Run the TFSWFSQZ program, and from the client, run DMJFOUQZ.

The output of TFSWFSQZ is shown here:

One server can give service to many clients. The XIJMF loop keeps the server program alive
and does not allow the code to end. You can set a connection limit to the XIJMF loop; for
example, set XIJMFJ  and increment J with each connection.

[ 17 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Before proceeding to the next example, the concept of CZUFBSSBZ should be understood.
The CZUFBSSBZ array is a mutable sequence of unsigned integers in the range of 0 to 255.
You can delete, insert, or replace arbitrary values or slices. The CZUFBSSBZ array's objects
can be created by calling the built-in CZUFBSSBZ array.

The general syntax of CZUFBSSBZ is as follows:


CZUFBSSBZ <TPVSDF<FODPEJOH<FSSPST>>>

Let's illustrate this with an example:


NCZUFBSSBZ .PIJU.PIJU
N<>

N<>

N<>)FMMP
N
CZUFBSSBZ C )FMMP.PIJU

This is an example of slicing the CZUFBSSBZ.

Now, let's look at the TQMJU operation on CZUFBSSBZ :


NCZUFBSSBZ )FMMP.PIJU
N
CZUFBSSBZ C )FMMP.PIJU
NTQMJU
<CZUFBSSBZ C )FMMP CZUFBSSBZ C .PIJU >

The following is the BQQFOE operation on CZUFBSSBZ :


NBQQFOE 
N
CZUFBSSBZ C )FMMP.PIJU
CZUFBSSBZ C )FMMP8PSME

The next example is of TSFDW@JOUP CVGG . In this example, we will use CZUFBSSBZ to
create a buffer to store data.

First, run the server-side code. Run TFSWFSQZ:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".

[ 18 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

TCJOE IPTUQPSU
TMJTUFO 
DPOOBEESTBDDFQU
QSJOUDPOOFDUFECZBEES
DPOOTFOE 5IBOLT
DPOODMPTF

The preceding program is the same as the previous one. In this program, the server sends
5IBOLT; six characters.

Let's run the client-side program. Run DMJFOUQZ:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
TDPOOFDU IPTUQPSU
CVGCZUFBSSBZ   CVGGFSDSFBUFE
QSJOU/VNCFSPG#ZUFTTSFDW@JOUP CVG
QSJOUCVG
TDMPTF

In the preceding program, a CVG parameter is created using CZUFBSSBZ . The


TSFDW@JOUP CVG statement gives us the number of bytes received. The CVG parameter
gives us the string received.

The output of DMJFOUQZ and TFSWFSQZ is shown in the following screenshot:

[ 19 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Our client program successfully received 6 bytes of the string, 5IBOLT. You must have an
idea of CZUFBSSBZ by now. I hope you will remember it.

This time, I will create a UDP socket.

Run VEQQZ, and we will discuss the code line by line:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@%(3".
TCJOE IPTUQPSU
EBUBBEESTSFDWGSPN 
QSJOUSFDFJWFEGSPNBEES
QSJOUPCUBJOFEEBUB
TDMPTF

TPDLFU40$,@%(3". creates a UDP socket, and EBUBBEESTSFDWGSPN 


returns two things, the first is the data and the second is the address of the source.

Now, see the client-side preparations. Run VEQQZ:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@%(3".
QSJOUTTFOEUP IFMMPBMM IPTUQPSU
TDMPTF

Here, I used the UDP socket and the TTFOEUP method, as you can see in the definition
of TPDLFUTFOEUP . You will know that UDP is a connectionless protocol, so there is no
need to establish a connection here.

[ 20 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

The following screenshot shows the output of VEQQZ (the UDP server) and VEQQZ (the
UDP client):

The server program successfully received data.

Let's assume that a server is running and that there is no client start connection, and that
the server will have been listening. So, to avoid this situation, use
TPDLFUTFUUJNFPVU WBMVF .

Generally, we give a value as an integer; if I give  as the value, this would mean wait for
five seconds. If the operation doesn't complete within five seconds, then a timeout
exception would be raised. You can also provide a non-negative float value.

For example, let's look at the following code:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@%(3".
TCJOE IPTUQPSU
TTFUUJNFPVU 
EBUBBEESTSFDWGSPN 
QSJOUSFDFWJFEGSPNBEES
QSJOUPCUBJOFEEBUB
TDMPTF

I added one extra line, that is, TTFUUJNFPVU  . The program waits for five seconds; only
after that will it give us an error message. Run VEQUJNFQZ.

[ 21 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

The output is shown in the following screenshot:

The program shows an error; however, it does not look good if it gives an error message.
The program should handle the exceptions.

Socket exceptions
In order to handle exceptions, we'll use the try and except blocks. The following example
will tell you how to handle the exceptions. Run VEQUJNFQZ:
JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@%(3".
USZ
TCJOE IPTUQPSU
TTFUUJNFPVU 
EBUBBEESTSFDWGSPN 
QSJOUSFDFWJFEGSPNBEES
QSJOUPCUBJOFEEBUB
TDMPTF
FYDFQUTPDLFUUJNFPVU
QSJOU$MJFOUOPUDPOOFDUFE
TDMPTF

The output is shown in the following screenshot:

[ 22 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

In the try block, I put my code, and from the except block, a customized message is printed
if any exception occurs.

Different types of exceptions are defined in Python's socket library for different errors.
These exceptions are described here:

FYDFQUJPOTPDLFUIFSSPS: This block catches the address-related error.


FYDFQUJPOTPDLFUUJNFPVU: This block catches the exception when a timeout
on a socket occurs, which has been enabled by TFUUJNFPVU . In the previous
example, you can see that we used TPDLFUUJNFPVU.
FYDFQUJPOTPDLFUHBJFSSPS: This block catches any exception that is raised
due to HFUBEESJOGP and HFUOBNFJOGP .
FYDFQUJPOTPDLFUFSSPS: This block catches any socket-related errors. If you
are not sure about any exception, you could use this. In other words, you can say
that it is a generic block and can catch any type of exception.

Downloading the example code

You can download the example code files from your account at IUUQ
XXXQBDLUQVCDPN for all of the Packt Publishing books you have
purchased. If you purchased this book elsewhere, you can visit IUUQ
XXXQBDLUQVCDPNTVQQPSU and register to have the files emailed directly
to you.

Useful socket methods


So far, you have gained knowledge of socket and client-server architecture. At this level,
you can make a small program of networks. However, the aim of this book is to test the
network and gather information. Python offers very beautiful as well as useful methods to
gather information. First, import the socket and then use these methods:

TPDLFUHFUIPTUCZOBNF IPTUOBNF : This method converts a hostname to the


IPv4 address format. The IPv4 address is returned in the form of a string. Here is
an example:
>>> import socket>>>
socket.gethostbyname('thapar.edu')'220.227.15.55'>>>>>>
socket.gethostbyname('google.com')'173.194.126.64'>>>

[ 23 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

I know you are thinking about the OTMPPLVQ command. Later, you will see more magic.

TPDLFUHFUIPTUCZOBNF@FY OBNF : This method converts a hostname to the


IPv4 address pattern. However, the advantage over the previous method is that
it gives all the IP addresses of the domain name. It returns a tuple (hostname,
canonical name, and IP_addrlist) where the hostname is given by us, the
canonical name is a (possibly empty) list of canonical hostnames of the server for
the same address, and IP_addrlist is a list of all of the available IP addresses of
the same hostname. Often, one domain name is hosted on many IP addresses to
balance the load of the server. Unfortunately, this method does not work for
IPv6. I hope you are well-acquainted with tuples, lists, and dictionaries. Let's
look at an example:
>>> socket.gethostbyname_ex('thapar.edu')('thapar.edu', [],
['14.139.242.100', '220.227.15.55'])>>>
socket.gethostbyname_ex('google.com')>>>('google.com', [],
['173.194.36.64', '173.194.36.71', '173.194.36.73',
'173.194.36.70',
'173.194.36.78', '173.194.36.66', '173.194.36.65',
'173.194.36.68',
'173.194.36.69', '173.194.36.72', '173.194.36.67'])>>>

It returns many IP addresses for a single domain name. This means that one domain such
as UIBQBSFEV or HPPHMFDPN runs on multiple IPs.

TPDLFUHFUIPTUOBNF : This returns the hostname of the system where the


Python interpreter is currently running:
>>> socket.gethostname()'eXtreme'

To glean the current machine's IP address by using the socket module, you can use the
following trick using HFUIPTUCZOBNF HFUIPTUOBNF :
>>> socket.gethostbyname(socket.gethostname())'192.168.10.1'>>>

You know that our computer has many interfaces. If you want to know the IP address of all
of the interfaces, use the extended interface:.
>>> socket.gethostbyname_ex(socket.gethostname())('eXtreme', [],
['10.0.0.10', '192.168.10.1', '192.168.0.1'])>>>

It returns one tuple containing three elements, the first is the machine name, the second is a
list of aliases for the hostname (empty, in this case,) and the third is the list of the IP
addresses of interfaces.

[ 24 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

TPDLFUHFUGREO <OBNF> : This is used to find the fully qualified domain name
if it's available. The fully qualified domain name consists of a host and domain
name; for example, CFUB might be the hostname, and FYBNQMFDPN might be the
domain name. The fully qualified domain name (FQDN) becomes
CFUBFYBNQMFDPN:

>>> socket.getfqdn('facebook.com')'edge-star-shv-12-
frc3.facebook.com'

In the preceding example, FEHFTUBSTIWGSD is the hostname, and GBDFCPPLDPN


is the domain name. In the following example, FQDN is not available for UIBQBSFEV:
>>> socket.getfqdn('thapar.edu')'thapar.edu'

If the name argument is blank, it returns the current machine name:


>>> socket.getfqdn()'eXtreme'>>>

TPDLFUHFUIPTUCZBEES JQ@BEESFTT : This is like a reverse lookup for the


name. It returns a tuple (hostname, canonical name, and IP_addrlist) where
hostname is the hostname that responds to the given JQ@BEESFTT, the canonical
name is a (possibly empty) list of canonical names of the same address, and
IP_addrlist is a list of IP addresses for the same network interface on the same
host:
>>> socket.gethostbyaddr('173.194.36.71')('del01s06-in-
f7.1e100.net', [], ['173.194.36.71'])>>>
socket.gethostbyaddr('119.18.50.66')Traceback (most recent call
last): File "<pyshell#9>", line 1, in <module>
socket.gethostbyaddr('119.18.50.66')herror: [Errno 11004] host
not found

It shows an error in the last query because reverse DNS lookup is not present.

TPDLFUHFUTFSWCZOBNF TFSWJDFOBNF<QSPUPDPM@OBNF> : This converts


any protocol name to the corresponding port number. The Protocol name is
optional, either TCP or UDP. For example, the DNS service uses TCP as well as
UDP connections. If the protocol name is not given, any protocol could match:
>>> import socket>>> socket.getservbyname('http')80>>>
socket.getservbyname('smtp','tcp')25>>>

[ 25 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

TPDLFUHFUTFSWCZQPSU QPSU<QSPUPDPM@OBNF> : This converts an internet


port number to the corresponding service name. The protocol name is optional,
either TCP or UDP:
>>> socket.getservbyport(80)'http'>>>
socket.getservbyport(23)'telnet'>>>
socket.getservbyport(445)'microsoft-ds'>>>

TPDLFUDPOOFDU@FY BEESFTT : This method returns an error indicator. If


successful, it returns ; otherwise, it returns the FSSOP variable. You can take
advantage of this function to scan the ports. Run the DPOOFDU@FYQZ program:
JNQPSUTPDLFU
SNJQ 
QPSUMJTU<>

GPSQPSUJOQPSUMJTU
TPDLTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
SFTVMUTPDLDPOOFDU@FY SNJQQPSU
QSJOUQPSUSFTVMU
TPDLDMPTF

The output is shown in the following screenshot:

The preceding program output shows that ports  , ,, and  are open. This is a
rudimentary port scanner. The program is using the IP address ; this is a
loopback address, so it is impossible to have any connectivity issues. However, when you
have issues, perform this on another device with a large port list. This time, you will have
to use TPDLFUTFUUJNFPVU WBMVF :
TPDLFUHFUBEESJOGP IPTUQPSU<GBNJMZ<TPDLUZQF<QSPUP<GMBHT>>>>

[ 26 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

This socket method converts the host and port arguments into a sequence of five tuples.

Let's take a look at the following example:


>>> import socket
>>> socket.getaddrinfo('www.thapar.edu', 'http')
[(2, 1, 0, '', ('220.227.15.47', 80)), (2, 1, 0, '',
('14.139.242.100', 80))]
>>>

Output  represents the family,  represents the socket type,  represents the protocol,
represents the canonical name, and   represents the  socket
address. However, this number is difficult to comprehend. Open the directory of the socket.

Use the following code to find the result in a readable form:


JNQPSUTPDLFU
EFGHFU@QSPUOVNCFS QSFGJY 
SFUVSOEJDU  HFUBUUS TPDLFUB B
GPSBJOEJS TPDLFU
JGBTUBSUTXJUI QSFGJY

QSPUP@GBNHFU@QSPUOVNCFS "'@
UZQFTHFU@QSPUOVNCFS 40$,@
QSPUPDPMTHFU@QSPUOVNCFS *113050@

GPSSFTJOTPDLFUHFUBEESJOGP XXXUIBQBSFEV  IUUQ 

GBNJMZTPDLUZQFQSPUPDBOPOOBNFTPDLBEESSFT

QSJOU 'BNJMZ QSPUP@GBN<GBNJMZ>


QSJOU 5ZQF UZQFT<TPDLUZQF>
QSJOU 1SPUPDPM QSPUPDPMT<QSPUP>
QSJOU $BOPOJDBMOBNF DBOPOOBNF
QSJOU 4PDLFUBEESFTT TPDLBEES

[ 27 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

The output of the code is shown in the following screenshot:

The upper part makes a dictionary using the "'@, 40$,@, and *113050@ prefixes that map
the protocol number to their names. This dictionary is formed by the list comprehension
technique.

The upper part of the code might be confusing sometimes, but we can execute the code
separately as follows:
>>> dict(( getattr(socket,n),n) for n in dir(socket) if
n.startswith('AF_'))
{0: 'AF_UNSPEC', 2: 'AF_INET', 6: 'AF_IPX', 11: 'AF_SNA', 12:
'AF_DECnet', 16: 'AF_APPLETALK', 23: 'AF_INET6', 26: 'AF_IRDA'}

Now, this is easy to understand. This code is usually used to get the protocol number:
GPSSFTJOTPDLFUHFUBEESJOGP XXXUIBQBSFEV  IUUQ 

The preceding line of code returns the five values, as discussed in the definition. These
values are then matched with their corresponding dictionary.

[ 28 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Summary
From reading this chapter, you have got an understanding of networking in Python. The
aim of this chapter was to complete the prerequisites of the upcoming chapters. From the
start, you have learned the need for pentesting. Pentesting is conducted to identify threats
and vulnerabilities in an organization. What should be tested? This is specified in the
agreement; don't try to test anything that is not mentioned in the agreement. The agreement
is your get out of jail free card. A pentester should have knowledge of the latest technology,
and you should have some knowledge of Python before you start reading this book. In
order to run Python scripts, you should have a lab setup, a network of computers to test a
live system, and dummy websites running on the Apache server.

This chapter also discussed the socket and its methods. The server socket method defines
how to make a simple server. The server binds its own address and port to listen to the
connections. A client that knows the server address and port number connects to the server
to get a service. Some socket methods such as TPDLFUSFDW CVGTJ[F ,
TPDLFUSFDWGSPN CVGTJ[F , TPDLFUSFDW@JOUP CVGGFS , TPDLFUTFOE CZUFT ,
and so on are useful for the server as well as the client. You learned how to handle different
types of exceptions. In the Useful socket methods section, you got an idea of how to get the IP
address and hostname of a machine, how to glean the IP address from the domain name,
and vice versa.

In the next chapter, we will be looking at scanning pentesting, which includes IP address
scanning to detect live hosts. To carry out IP scanning, ping sweep and TCP scanning are
used. You will learn how to detect services running on a remote host using a port scanner.

[ 29 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

2
Scanning Pentesting
Network scanning refers to a set of procedures that investigate a live host, the type of host,
open ports, and the type of services running on the host. Network scanning is a part of
intelligence gathering by virtue of which an attacker can create a profile of the target
organization.

In this chapter, we will cover the following topics:

How to check live systems


Ping sweep
TCP scanner
How to create an efficient IP scanner
Services running on the target machine
The concept of a port scanner
How to create an efficient port scanner

You should have a basic knowledge of the TCP/IP layer communication. Before proceeding
further, the concept of the protocol data unit (PDU) should be clear.

PDU is a unit of data specified in the protocol. It is the generic term for data at each layer:

For the application layer, PDU indicates data


For the transport layer, PDU indicates a segment
For the internet or the network layer, PDU indicates a packet
For the data link layer or network access layer, PDU indicates a frame
For the physical layer, that is, physical transmission, PDU indicates bits

||||||||||||||||||||
||||||||||||||||||||

Scanning Pentesting Chapter 2

How to check live systems in a network and


the concept of a live system
A ping scan involves sending an ICMP ECHO Request to a host. If a host is live, it will
return an ICMP ECHO Reply, as shown in the following diagram:

+%/2TGSWGUVCPFTGRN[

The operating system's QJOH command provides the facility to check whether the host is
live or not. Consider a situation where you have to test a full list of IP addresses. In this
situation, if you test the IP addresses one by one, it will take a lot of time and effort. In
order to handle this situation, we use ping sweep.

Ping sweep
Ping sweep is used to identify the live host from a range of IP addresses by sending the
ICMP ECHO request and the ICMP ECHO reply. From a subnet and network address, an
attacker or pentester can calculate the network range. In this section, I am going to
demonstrate how to take advantage of the ping facility of an operating system.

First, I shall write a simple and small piece of code, as follows:


JNQPSUPT
SFTQPOTFPTQPQFO QJOHO
GPSMJOFJOSFTQPOTFSFBEMJOFT 
QSJOUMJOF

[ 31 ]

Technet24
||||||||||||||||||||
Exploring the Variety of Random
Documents with Different Content
angustie dell'esercito alemanno in Italia, perchè l'elettor bavaro
cresciuto cotanto di forze entrò nel Tirolo, e giunse ad impossessarsi
della capitale d'Inspruch. L'avrebbe bene accomodato il possesso e
dominio di quella provincia confinante ai suoi Stati; ma si
aggiugnevano due altre mire, l'una di togliere ai Tedeschi quella
strada per cui solevano spignere in Italia i soccorsi di milizie, e l'altra
di aprirsi un libero commercio coll'esercito franzese, esistente in
Italia, affin di riceverne più facilmente gli occorrenti sussidii.
Mossesi infatti il duca di Vandomo nel mese d'agosto dalla
Lombardia con parte del suo esercito alla volta del Trentino,
sperando di toccar la mano ai Bavaresi, che avevano da venirgli
incontro. Marciarono i Franzesi per Monte Baldo e per le rive del lago
di Garda, e cominciarono ad aggrapparsi per quelle montagne, con
impadronirsi delle castella di Torbole, Nago, Bretonico e d'altre, che
non fecero difesa, a riserva del castello d'Arco, il quale per cinque
giorni sostenne l'empito de' cannoni nemici, con fatiche incredibili fin
colà strascinati. Giunse poi sul fine d'agosto dopo mille stenti
l'esercito franzese alla vista di Trento, ma coll'Adige frapposto, e con
gli abitanti nell'opposta riva preparati a contrastare gli ulteriori
avanzamenti dei nemici. Nè le minaccie del Vandomo, nè molte
bombe avventate contro la città atterrirono punto i Trentini, e
massimamente dacchè in aiuto loro accorse con alcuni reggimenti
cesarei il generale conte Solari. All'aspetto di questi movimenti,
comune credenza era in Italia che in breve si avessero a vedere in
precipizio gli affari dell'imperadore, fatta che fosse l'unione del
Bavaro col duca di Vandomo. Stettero poco a disingannarsi al
comparire all'improvviso mutata tutta la scena. I Tirolesi d'antico
odio pregni contra de' Bavaresi, e massimamente i bravi lor
cacciatori, sì fattamente cominciarono a ristrignere e tempestar coi
loro fucili le truppe nemiche, prendendo spezialmente di mira gli
uffiziali, che altro scampo non ebbe l'elettore, se non quello di
ritirarsi alle sue contrade. Medesimamente non senza maraviglia dei
politici fu osservato ritornarsene il duca di Vandomo in Italia, dopo
aver sacrificato inutilmente di gran gente e munizioni in quella
infelice spedizione. Ora ecco il motivo di sua ritirata.
Non avea mai potuto Vittorio Amedeo duca di Savoia, siccome
principe di mirabile accortezza, e attentissimo non meno al presente
che ai futuri tempi, mirar senza ribrezzo la tanto accresciuta
grandezza della real casa di Francia, e parevagli fabbricato il
mortorio alla sua sovranità, dacchè il ducato di Milano era caduto in
mano d'un monarca sì congiunto di sangue colla potenza franzese.
Portò la congiuntura dei tempi ch'egli si avesse a collegar colle due
corone, tuttochè scorgesse così fatta lega troppo contraria ai proprii
interessi; ma stava egli sempre sospirando il tempo di poter rompere
questa catena; e parve ora venuto, dacchè era vicino a spirare il
tempo del contratto impegno della sua lega coi re di Francia e di
Spagna. Non lasciava la corte cesarea di far buona cera a questo
principe, benchè in apparenza nemico, nè sul principio della rottura
scacciò da Vienna il di lui ministro, come avea praticato con quello
del duca di Mantova. Spedì eziandio nel luglio dell'anno presente a
Torino (per quanto pretesero i Franzesi) il conte di Aversbergh
travestito per intavolare con lui qualche trattato, ma senza sapersi se
ne seguisse conclusione alcuna finora. Quel che è certo, non avea
voluto il duca permettere che le sue truppe passassero verso il
Trentino. Ora i forti sospetti conceputi nella creduta vacillante fede
del duca Vittorio Amedeo diedero impulso al re Cristianissimo di
richiamare in Lombardia il duca di Vandomo. Tornato questo
generale colle sue genti a San Benedetto di Mantova di qua dal Po,
già da lui scelto per suo quartier generale, nel dì 28 oppure 29 di
settembre, messo in armi tutto l'esercito suo, fece disarmar le truppe
di Savoia che si trovavano in quel campo ed altri luoghi, ritenendo
prigioni tutti gli uffiziali e soldati. Non erano più di tre mila; altri
nondimeno li fecero ascendere a quattro o a cinquemila. Per questa
impensata novità e violenza alterato al maggior segno il duca,
principe di grande animo, ne fece alte doglianze per tutte le corti;
mise le guardie in Torino agli ambasciatori di Francia e Spagna;
occupò gran copia d'armi spedite dalla Francia in Italia, ed
imprigionò quanti Franzesi potè cogliere nei suoi Stati. Quindi si
diede precipitosamente a premunirsi e a mettere in armi tutti i suoi
sudditi, per resistere al temporale che andava a scaricarsi sopra i
suoi Stati; giacchè non tardò il duca di Vandomo a mettere in viaggio
buona parte dell'esercito suo contro il Piemonte. Saltò fuori in tal
guisa un nuovo nemico delle due corone, e un nuovo teatro di
guerra in Italia.
Nel dì 5 di dicembre pubblicamente dichiarò il re di Francia Luigi
XIV la guerra contra di esso duca di Savoia, i il quale nel dì 25 di
ottobre, come scrisse taluno, o piuttosto nel dì 8 di novembre, come
ha lo strumento rapportato dal Lunig, avea già stretta lega
coll'imperadore Leopoldo. In esso strumento si vede promesso al
duca Vittorio Amedeo tutto il Monferrato, spettante al duca di
Mantova con Casale, e inoltre Alessandria, Valenza, la Valsesia e la
Lomellina, con obbligo di demolir le fortificazioni di Mortara.
Promettevano inoltre le potenze marittime un sussidio mensile di
ottanta mila ducati di banco ad esso principe, durante la guerra. Fu
poi aggiunto un altro alquanto imbrogliato articolo della cessione
ancora del Vigevanasco, per cui col tempo seguirono molte dispute
colla corte di Vienna. Per essersi trovato il duca colto all'improvviso
dallo sdegno franzese, e specialmente sprovveduto di cavalleria, gli
convenne ricorrere al generale conte di Staremberg, il quale,
desideroso di assistere il nuovo alleato, mise improvvisamente in
viaggio, nel dì 20 di ottobre, mille cinquecento cavalli sotto il
comando del generale marchese Annibale Visconti. Benchè sollecita
fosse la lor marcia, più solleciti furono gli avvisi al duca di Vandomo
del lor disegno; laonde ben guernito di milizia il passo della
Stradella, Serravalle ed altri siti, allorchè colà giunsero gli affaticati
Alemanni, trovarono un terribil fuoco, e andarono presto in rotta.
Molti furono gli uccisi, molti i prigioni, ed a quei che colla fuga si
sottrassero al cimento, convenne dipoi passare fino a San Pier di
Arena presso Genova, e valicare aspre montagne per giugnere in
Piemonte. Questo picciolo rinforzo, e l'essere stati i Franzesi, a
cagion del suddetto passaggio, impegnati in varii movimenti, servì di
non lieve respiro al duca di Savoia; ma non già a preservarlo
dagl'insulti a lui minacciati dal potente nemico. Il perchè determinò
in fine il saggio conte Guido di Staremberg un'arditissima impresa,
che, per essere felicemente riuscita, riportò poscia il plauso
d'ognuno. Quando si pensava la gente che l'esercito suo, postato sul
Modenese e Mantovano di qua da Po, si fosse ben adagiato nei
quartieri d'inverno e pensasse al riposo, all'improvvisa con circa dieci
mila fanti e quattro mila cavalli, seco menando sedici cannoni, nel
giorno santo del Natale passò esso Staremberg la Secchia, e pel
Carpigiano s'indirizzò alla strada maestra chiamata Claudia,
prendendo pel Reggiano e Parmigiano con marcie sforzate il
cammino alla volta del Piemonte, senza far caso dei rigori della
stagione, delle strade rotte e di tanti fiumi gravidi di acqua che
conveniva passare. Era già tornato il duca di Vandomo al campo di
San Benedetto di Mantova. Al primo avviso di questo impensato
movimento dei nemici, raunate le sue truppe, si diede ad inseguirli
con forze, chi disse minori, e chi maggiori, ma senza poter mai
raggiugnerli, oppure senza mai volerli raggiugnere, per poca voglia
di azzardare una battaglia. Si contarono bensì alcune scaramucce ed
incontri, nei quali lasciarono la vita i due valorosi generali Lictenstein
Tedesco e Solari Italiano; ma questi non poterono impedire al prode
comandante di felicemente superar tutti i disagi, e di pervenire ad
unirsi col duca di Savoia nel dì 13 del seguente gennaio, con infinita
consolazione di lui e de' sudditi suoi.
Presero in questi tempi, cioè nel dì 8 di dicembre, i Franzesi
dimoranti in Modena il pretesto di confiscare al duca Rinaldo d'Este
tutte le sue rendite e mobili, perchè il suo ministro in Vienna,
trovandosi nell'anticamera della regina de' Romani, in passando
l'arciduca Carlo, dichiarato re di Spagna, l'inchinò. A chi vuol far del
male, ogni cosa gli fa giuoco. Entrato nel novembre il maresciallo di
Tessè nella Savoia, s'impadronì di Sciambery sua capitale, e poscia
strinse con un blocco la fortezza di Monmegliano. Riuscì in
quest'anno alle potenze marittime e all'imperatore Leopoldo di ritirar
seco in lega un'altra potenza, cioè Pietro II re di Portogallo. Gli
articoli di questa alleanza furono sottoscritti nel dì 16 di maggio, e
fatte di grandi promesse a quel monarca, fondate nondimeno sugli
incerti avvenimenti delle guerre. Di qui sorsero speranze ne' collegati
di potere un dì detronizzare il re di Spagna Filippo V, al qual fine
creduto fu non solamente utile, ma necessario, che lo stesso
arciduca Carlo, proclamato re di Spagna col nome di Carlo III,
passasse in persona colà per dar polso ai Portoghesi, e per animare
l'occulto partito austriaco che si conservava tuttavia nei regni di
Spagna. Pertanto questo savio, affabile e piissimo principe, preso
congedo dagli augusti lagrimanti suoi genitori e dal fratello Giuseppe
re de' Romani, si mise nel settembre in viaggio alla volta dell'Olanda,
con ricevere immensi onori per dovunque passò. Pertanto ecco
oramai gran parte dell'Europa in guerra per disputare della
monarchia di Spagna; nel qual tempo anche il Settentrione ardeva
tutto di guerra per la lega del Sassone re di Polonia collo czar della
Russia contro il re di Svezia, che diede lor delle aspre lezioni. Presero
in quest'anno i Franzesi Brisac, ricuperarono Landau, diedero una
rotta ai Tedeschi sotto esso Landau; e all'incontro gli Anglolandi
s'impadronirono di Bona, Huz e Limburgo.
Cristo mdcciv. Indizione xii.
Anno di Clemente XI papa 5.
Leopoldo imperadore 47.

Veggendosi Rinaldo d'Este duca di Modena sì maltrattato ed


oppresso dai Franzesi, altro ripiego non trovò che di ricorrere a papa
Clemente XI per implorare i suoi paterni uffizii appresso le due
corone, o, per dir meglio, alla corte di Francia, che sola dirigeva la
gran macchina, e sotto nome del re Cattolico sola signoreggiava
negli Stati d'esso duca. Si portò a questo fine incognito a Roma, e vi
si fermò per più mesi. Giacchè non volle indursi a gittarsi in braccio
a' Franzesi, non altro in fine potè ottenere che una pensione di dieci
mila doble; e questa ancora gli convenne comperare con cedere ad
essi Franzesi il possesso della provincia della Garfagnana, situata di
là dall'Apennino colla fortezza di Montalfonso; unico resto de' suoi
dominii, finora sostenuto nel suo naufragio: dopo di che si restituì a
Bologna ad aspettare senza avvilirsi lo scioglimento dell'universal
tragedia. Ma alle sue disavventure si aggiunse in quest'anno la
demolizione della sua fortezza di Brescello, fatta dai Parmigiani:
tanto pontò il duca di Parma, per levarsi quello stecco dagli occhi.
Furono asportate parte a Mantova, parte nello Stato di Milano tutte
quelle artiglierie e attrezzi militari. Cominciarono in quest'anno a
declinar forte in Italia gli affari dell'imperadore e del collegato duca
di Savoia. L'incendio commosso in Ungheria dai sollevati, e in
Germania da Massimiliano elettor di Baviera, siccome quello che più
scottava la corte di Vienna, a lei non permetteva di alimentar la sua
armata in Italia coi necessari rinforzi di truppe e danaro. Nulla
all'incontro mancava al general franzese duca di Vandomo. Da che fu
egli maggiormente rinvigorito dalle nuove leve spedite dalla
Provenza per mare, divise l'esercito suo in due, ritenendo per sè le
forze maggiori a fine di far guerra al duca di Savoia; e dell'altra parte
diede il comando al gran priore duca di Vandomo suo fratello,
acciocchè tentasse di cacciar d'Italia il corpo di Tedeschi che assai
smilzo restava nel Mantovano di qua da Po, e teneva forte tuttavia la
terra di Ostiglia di là da esso fiume. Allorchè i Franzesi s'avviarono,
sul fine dell'anno precedente, dietro al conte Staremberg, aveano gli
Alemanni occupato Bomporto e la Bastia sul Modenese, con far
prigioniere il presidio di questa ultima. Tornato che fu a Modena il
generale signor di San Fremond, non perdè tempo a ricuperare, sul
principio di febbraio, quei luoghi: sicchè si ritirarono i Tedeschi alla
Mirandola, e attesero a fortificarsi in Revere, Ostiglia ed altri siti
lungo il Po di qua e di là, con istendersi ancora sul Ferrarese a
Figheruolo.
Venuto il mese d'aprile, si mosse il gran priore di Vandomo col
grosso delle sue milizie per isloggiare i Tedeschi da Revere. Non
l'aspettarono essi, e si ridussero di là da Po ad Ostiglia: con che
venne a restar separata la Mirandola dal campo loro. Allora fu che il
giovane Francesco Pico duca di essa Mirandola, accompagnato dal
principe Giovanni suo zio, e da don Tommaso d'Aquino Napoletano,
suo padrigno, e principe di Castiglione, comparve a Modena, con
dichiararsi del partito delle due corone, e con pubblicare un
manifesto contra dei cesarei. Fu bloccata da lì innanzi quella città da'
Franzesi; fu anche, sul fine di luglio, regalata da una buona pioggia
di bombe, ma senza suo gran danno, e senza che se ne
sgomentasse punto il conte di Koningsegg comandante in essa.
Pensavano intanto i troppo indeboliti Tedeschi, ridotti di là dal Po, a
mantenere almeno la comunicazione colla Germania; al qual fine
fortificarono Serravalle, Ponte Molino, e varii posti sotto Legnago
negli Stati della repubblica veneta. Di qua dal Po stavano i Franzesi,
cannonando incessantemente Ostiglia nell'opposta riva. Il gran priore
passò dipoi ad assediar Serravalle. Ma perciocchè non men le sue
truppe di qua dal fiume suddetto e i Tedeschi dall'altra parte si
stendevano sul Ferrarese, diede ciò motivo al sommo pontefice di
farne gravi querele per mezzo del cardinale Astalli legato di Ferrara,
intimando agli uni e agli altri di sloggiare, e nello stesso tempo
minacciando di unir le sue truppe colla parte ubbidiente per
iscacciarne la disubbidiente. Sì questi che quelli si mostrarono pronti
ad evacuare il Ferrarese, e in fatti si ritirarono i Franzesi dalla
Stellata, e gli Alemanni consegnarono Figheruolo agli uffiziali del
papa, con promesse di ritirarsi sul Veneziano. Mentre si allestivano a
partire, nella notte precedente la natività di san Giovanni Batista,
avendo i Franzesi raunata gran copia di barche, o trovate in Po, o
fatte venir dal Panaro, alcune migliaia di essi, imbarcati alle
Quadrelle, quetamente passarono di là dal fiume, ed ottenuto il
passo dalle guardie pontificie, diedero addosso agli Alemanni, i quali,
in vigore dell'accordo fatto se ne stavano assai spensierati e quieti.
Alquanti ne furono uccisi, gli altri colla fuga scamparono; restò il loro
bagaglio in man de' Franzesi. Fu cagion questo colpo ch'eglino
poscia abbandonassero Ostiglia, Serravalle e Ponte Molino, e che il
picciolo loro esercito, valicato l'Adige, andasse a mettersi in salvo sul
Trentino. Proruppe la corte di Vienna in escandescenze per questo
fatto, con pretendere di aver pruove chiare che fosse seguito di
concerto coi ministri del papa, perchè nello stesso tempo era andato
il conte Paolucci generale pontificio ad abboccarsi col gran priore, e
per altre ragioni che non importa riferire. Commosso dalle amare
doglianze di Cesare, il pontefice spedì a Ferrara monsignor Lorenzo
Corsini, che fu poi cardinale e papa, acciocchè ne formasse un
processo. Nulla risultò da questo che i pontifizii avessero consentito
o contribuito alla cacciata de' Tedeschi; ma non perciò si potè levar
di capo alla corte cesarea che il papa, assicurato oramai della fortuna
favorevole ai Gallispani, avesse data mano ad essi per cacciare lungi
da' suoi Stati quel molesto pugno di gente. Da che si trovarono
rinforzati gli Alemanni da alquante milizie calate dal Tirolo, dopo la
metà di settembre calarono di nuovo nel Bresciano, fortificandosi a
Gavardo e Salò sul lago di Garda, e in altri luoghi. Poche son le
nazioni e i principi che nelle prosperità sappiano conservar la
moderazione. Cadde allora in pensiero ai Franzesi di parlar alto, e di
obbligar la repubblica veneta ad impedire la calata e la dimora delle
soldatesche alemanne ne' suoi stati. E perciocchè la saviezza veneta,
risoluta di conservare la già presa neutralità, rispose con non minore
coraggio, e vieppiù rinforzò i presidii delle sue piazze, allora il gran
priore per forza entrò in Montechiaro, Calcinato, Carpanedolo,
Desenzano, Sermione ed altri luoghi, e non si guardò di far altre
insolenze e danni a quelle venete contrade, finchè arrivò il verno che
mise freno alle operazioni militari.
Quanto al Piemonte, avea bene il duca Vittorio Amedeo, con varie
leve fatte nei suoi Stati e negli Svizzeri, accresciuto di molto l'esercito
suo, ma per la gran copia di Franzesi, venuta per mare al duca di
Vandomo, si trovò sempre di troppo inferiore alle forze nemiche. Sul
principio di maggio contò esso Vandomo circa trentasei mila
combattenti nell'oste sua, e però, con isprezzo degli alleati postati a
Trino, passò in faccia di essi il Po, e gli obbligò a ritirarsi con qualche
loro perdita. Poi imprese l'assedio di Vercelli, città che, quantunque
presidiata da sei mila persone, non fece che una misera difesa; ed
ostinatosi il Vandomo a voler prigioniera di guerra quella guernigione
a fine di sempre più tagliar le penne al duca di Savoia, trovò
comandanti ed uffiziali che condiscesero a cedergli la piazza con sì
dura condizione. Ordine emanò ben tosto di spogliar quella città di
ogni fortificazione nel dì 21 di luglio. Calato intanto anche il duca
della Fogliada dal Delfinato con dieci mila combattenti, dopo essersi
impossessato della città di Susa, mise l'assedio a quel castello;
espugnò la Brunetta e il forte di Catinat; e nel dì 12 di luglio
costrinse il presidio del suddetto castello di Susa a rendersi con patti
molto onorevoli. Obbligò dipoi colla forza i Barbetti abitanti nelle
quattro valli ad accettare la neutralità. Andò quindi ad unirsi sotto la
città d'Ivrea col Vandomo, il quale sedici giorni impiegò a
sottomettere quella città. Ritiratosi il comandante nella cittadella,
poscia, nel dì 29 di settembre, dovette cedere, con restar prigioniere
egli e tutti i suoi. Vi restava in quelle parti la città d'Aosta renitente
alla fortuna; ma nè pur essa potè esimersi dall'ubbidire ai Franzesi
insieme col forte di Bard: con che restò precluso al duca di Savoia il
passo per ricevere soccorsi dalla parte della Germania e degli
Svizzeri. E pure qui non finirono le imprese dell'infaticabil duca di
Vandomo. Si avvisò egli, al dispetto della contraria stagione che si
appressava, d'imprendere l'assedio di Verrua, fortezza non solo pel
sito, perchè posta sul Po sopra un dirupato sasso ma eziandio per le
fortificazioni aggiunte, creduta quasi inespugnabile; e tanto più
perchè il duca di Savoia unito al maresciallo di Staremberg colla sua
armata stava postato di là dal Po a Crescentino nella riva opposta del
fiume, e mercè di tre ponti manteneva la comunicazione con Verrua.
Oltre a ciò, davanti a Verrua si trovava il posto di Guerbignano ben
trincerato e difeso da cinque mila fra Tedeschi e Piemontesi. Non si
atterrì per tutte queste difficoltà il Vandomo, e alla metà di ottobre
andò a piantare il campo contro di Guerbignano. Intanto perchè sì
fattamente calarono le acque del Po, che si poteano guadare, finse,
o pure determinò egli di voler passare col meglio delle sue genti, ed
assalire il campo di Crescentino. Ne fu avvisato a tempo il duca di
Savoia, che perciò richiamò la maggior parte della gente posta alla
difesa di Guerbignano. Tra la partenza di queste truppe e il fuoco di
molte mine che fecero saltare i trincieramenti di quel posto, il
Vandomo se ne impadronì, e dipoi si diede agli approcci e alle
batterie contro Verrua, continuando pertinacemente l'assedio pel
resto dell'anno; assedio memorabile non men per le incredibili offese
degli uni, che per l'insigne difesa e bravura degli altri.
Era mancata di vita nell'anno precedente Anna Isabella duchessa
di Mantova, moglie di Ferdinando Carlo Gonzaga duca regnante:
principessa che per la somma sua pietà, carità e pazienza meritò
vivendo e morta gli encomii d'ognuno. Volle in quest'anno esso duca
portarsi alla corte di Parigi, dove non gli mancarono onori e carezze
quante ne volle. Ottenne anche il titolo di generalissimo delle armate
in Italia di sua maestà Cristianissima. O il suo desiderio di lasciar
dopo di sè qualche posterità legittima, giacchè di questa era privo, o
le premure dei suoi domestici, e fors'anche della corte stessa di
Francia, lo invaghirono di passare alle seconde nozze. Si fermarono i
suoi voti sopra Susanna Enrichetta di Lorena, figlia di Carlo duca di
Elboeuf, principessa dotata al pari di beltà che di saviezza. Tornato
poi in Italia, arrivò nel dì 28 d'ottobre al campo del duca di
Vandomo, ricevuto ivi con sommo onore qual generalissimo, e
applaudito dal rimbombo di tutte le artiglierie. Condotta la novella
sua sposa per mare da quattro galee di Francia, corse gran rischio,
perchè malamente salutata da più cannonate di due armatori inglesi
presso Genova. Si celebrò poscia il suo maritaggio in Toscana nel dì
8 di novembre coll'assistenza del principe e principessa di
Vaudemont suoi parenti. Ma il duca, che avea logorata la sua sanità
nei passati disordini, nè pur trasse prole da questa degna
principessa. Ora mentre l'Italia mirava in ben cattiva situazione l'armi
cesaree e savoiarde, con prevalere cotanto le franzesi, cominciò la
fortuna a mutar volto in Germania. Avea l'elettor di Baviera slargate
molto l'ali, con essersi impadronito anche di Ratisbona, Augusta,
Passavia ed altri luoghi, e minacciava conquiste maggiori: quando
con segreta risoluzione fu spedito da Anna regina d'Inghilterra il suo
generale milord Marlboroug con isforzate marcie ad unir le sue forze
colle cesaree, comandate dal principe Eugenio in Germania. Non
mancò il re Cristianissimo d'inviare anch'egli in aiuto del Bavaro il
maresciallo di Tallard con ventidue mila combattenti. Occuparono i
due prodi generali anglocesarei la città di Donavert con un
combattimento, in cui grande fu il macello dei vinti, e forse non
minore quello dei vincitori.
Erano le due armate nemiche forti ciascuna di quasi sessanta
mila persone, e nel dì 13 d'agosto in vicinanza di Hogstedt vennero
alle mani. Da gran tempo non era seguita una sì terribil battaglia;
dall'una parte e dall'altra si combattè con estremo valore e furore;
ma in fine si dichiarò la vittoria in favore degl'imperiali ed Inglesi.
Secondo le relazioni tedesche d'allora, dieci mila Gallo-Bavari vi
perderono la vita, sei mila se ne andarono feriti, e dodici o
quattordici mila rimasero prigioni, la maggior parte colti separati
dall'armata e stretti dal Danubio, che furono forzati a posar le armi.
Fra essi prigionieri si contò il maresciallo di Tallard. Il duca di Baviera
e il maresciallo di Marsin, colla gente che poterono salvare,
frettolosamente marciarono alla volta della Selva Nera e della
Francia. Anche l'esercito vittorioso lasciò sul campo circa cinque mila
estinti, e a più di sette mila ascese il numero de' feriti. Le
conseguenze di sì gran vittoria furono la liberazion d'Augusta, Ulma
ed altre città della Germania, e l'acquisto di nuovo di quella di
Landau in Alsazia. La Baviera, che dianzi facea tremar Vienna stessa,
venne in potere di Cesare con patti onorevoli per la elettrice, che si
ritirò poi a Venezia, essendo passato l'elettore consorte al suo
governo di Fiandra. Al primo avviso di quella sanguinosa battaglia
portato in Italia, si adirarono forte i Franzesi, con chi riferiva essersi
rendute prigioniere tante migliaia de' lor nazionali senza fare difesa.
Si accertarono poi della verità con loro grande rammarico. Ed ecco la
prima amara lezione che riportò delle sue vaste idee il re
Cristianissimo Luigi XIV. Fu ancora gran guerra in Portogallo, dove
era giunto il re Carlo III con rinforzi di milizie inglesi ed olandesi.
Andò in campagna lo stesso re Filippo V; riportò di molti vantaggi
sopra de' Portoghesi, e se ne tornò glorioso a Madrid; se non che le
sue allegrezze restarono amareggiate dall'avere gl'Inglesi occupata la
città di Gibilterra, posto di somma importanza nello stretto, ma posto
mal custodito dagli Spagnuoli in sì pericolosa congiuntura. Tentarono
essi di ricuperarlo con un vigoroso assedio, che durò sino all'anno
seguente, ma senza poterne snidare di colà i nemici, che anche
oggidì ne conservano il dominio. Seguì parimente una fiera battaglia
circa il fine d'agosto verso Malega fra le flotte franzese ed
anglolanda. Sì gli uni che gli altri solennizzarono dipoi col Te Deum la
vittoria, che ognun si attribuì, e niuno veramente riportò. Nel dì 23 di
febbraio di quest'anno mancò di vita in Roma il cardinale Enrico
Noris Veronese, ben degno che di lui si faccia menzione in queste
memorie. Militò egli nell'ordine dei frati agostiniani, fu pubblico
lettore in Pisa, e custode della biblioteca Vaticana; poi promosso alla
sacra porpora nel 1695; personaggio che pel sodo ingegno, raro
giudizio e profonda erudizione non ebbe pari in Italia ai tempi suoi,
come ne fanno e faran sempre fede le opere da lui date alla luce.
Cristo mdccv. Indizione xiii.
Anno di Clemente XI papa 6.
Giuseppe imperadore 1.

Fu questo l'ultimo anno della vita di Leopoldo Austriaco


imperadore, morto nel dì 5 di maggio: monarca, ne' cui elogii si
stancarono giustamente le penne di molti storici. La pietà, retaggio
singolare dell'augusta casa d'Austria, in lui principalmente si vide
risplendere, e del pari la clemenza, la affabilità e la liberalità
massimamente verso dei poveri. Mai non si vide in lui alterigia nelle
prospere cose, non mai abbattimento di spirito nelle avverse. Parea
che nelle disavventure non gli mancasse mai qualche miracolo in
saccoccia per risorgere. Lasciò un gran desiderio di sè, e insieme due
figli, l'uno Giuseppe, re da molti anni de' Romani, e Carlo III
appellato re di Spagna, il primo di temperamento focoso, e l'altro di
una mirabil saviezza. A lui succedette il primo con assumere,
secondo il rito, il titolo d'imperador de' Romani, ed accudire al pari,
anzi più del padre defunto, al proseguimento della guerra contro la
real casa di Francia. Pubblicò nel luglio di quest'anno il pontefice
Clemente XI una nuova bolla contra de' giansenisti. Ma sotto il
novello imperadore Giuseppe crebbero le amarezze della corte
pontificia, di maniera che il conte di Lemberg ambasciatore cesareo
in Roma se ne partì, passando in Toscana, e fu licenziato da Vienna
monsignore Davia Bolognese nunzio di sua santità. Gran tempo era
che il magnanimo pontefice pensava ad accrescere un nuovo
ornamento alla città di Roma coll'erezione della colonna Antoniana;
perciò diede l'ordine che fosse disotterrata. Nel dì 25 di settembre fu
questo bel monumento solamente cavato dal terreno per opera del
cavalier Fontana; e gran somma d'oro costò sì nobile impresa.
In Piemonte continuò ancora gran tempo la forte piazza di Verrua
a sostenersi contro le incessanti offese del campo franzese. Nel dì 26
di dicembre dell'anno precedente un gran guasto fu dato alle trincee
degli assedianti da quel presidio, rinforzato segretamente dal duca di
Savoia da due mila persone, giacchè egli manteneva tuttavia la
comunicazion colla fortezza mediante il ponte di Crescentino: ma
senza comparazione più furono i periti nel campo d'essi Franzesi a
cagion dei gravi patimenti di un assedio ostinatamente sostenuto in
mezzo ai rigori del verno, ancorchè non ommettesse il duca di
Vandomo diligenza alcuna per animarli con profusion di danaro e di
alimenti. Intanto innumerabili furono gli sforzi delle artiglierie,
bombe e fuochi artifiziali contro l'ostinata piazza per li mesi di
gennaio e febbraio. Frequenti erano ancora le mine e i fornelli sì
dell'una che dall'altra parte. Ma perciocchè si conobbe troppo difficile
il vincere questa pugna, finchè il duca Vittorio Amedeo potesse
dall'opposta riva del Po andare rinfrescando quella fortezza di nuovi
combattenti, viveri e munizioni; nel primo dì di marzo il Vandomo
improvvisamente spinse un grosso distaccamento ad occupar l'isola
e forte del Po, a cui si atteneva il ponte nemico; e così tagliò ogni
comunicazione con Verrua. Ritirossi allora il duca di Savoia col
maresciallo di Staremberg a Civasso, lasciando Crescentino in poter
de' Franzesi. Si trovò in breve il valoroso comandante di Verrua
obbligato a cedere; ma prima di farlo, co' fornelli preparati mandò in
aria i recinti e bastioni, e poi si rendè nel dì 10 di marzo a
discrezione, rimproverato poscia e insieme lodato dal Vandorno per
sì lunga e gloriosa difesa. Presero dopo tale acquisto le affaticate
milizie franzesi riposo fino al principio di giugno, ed allora, uscendo
in campagna, si mossero con disegno di assediare Civasso; e di
aprirsi con ciò il campo fino a Torino, già meditando offese contra di
quella capitale. Stava accampato in quelle vicinanze il duca di Savoia
con lo Staremberg, e di là diede molte percosse alle truppe franzesi,
ma senza poter impedire l'assedio di Civasso. Si sostenne questa
picciola piazza sino al 29 di luglio, in cui esso duca alla sordina fece
di notte evacuarla, per quanto potè, di artiglierie e munizioni, e la
lasciò in potere del duca della Fogliada, comandante allora di
quell'armata franzese, giacchè il duca di Vandomo avea dovuto
accorrere al basso Po contro l'armata cesarea, siccome diremo.
Di grandi ed incredibili preparamenti fece dipoi esso Fogliada,
passato sino alla Veneria, per mettere l'assedio a Torino; ma perchè
sopraggiunsero ordini dal re Cristianissimo di differire sì grande
impresa all'anno seguente, portò egli la guerra altrove. Avea questo
general franzese molto prima, cioè nel dì 10 di marzo, obbligata a
rendersi la picciola città di Villafranca sulle rive del Mediterraneo.
Lasciato poscia un blocco intorno a quella cittadella, che poi si
arrendè nel dì primo di aprile, andò ad aprir la trincea sotto la città
di Nizza. Se ne impadronirono i Franzesi, ma non vedendo maniera
di forzare quel castello, l'abbandonarono di poi con rovinare le
fortificazioni. Da che queste furono alquanto ristorate dal marchese
di Caraglio governatore, sul principio di novembre comparve colà di
nuovo con forze maggiori il duca di Berwich, ed entratovi nel dì 14 di
esso mese, si accinse poi a far giocare le batterie contra di quel
castello, il quale non meno pel sito che per le fortificazioni atto era a
far buona resistenza. Aveano, per non so qual ordine male inteso, i
Franzesi ritirata la lor guarnigione da Asti verso la metà d'ottobre. Vi
accorse tosto il maresciallo di Staremberg, e piantò quivi il suo
quartiere. Tanto ardire non piacendo al duca della Fogliada, andò ad
accamparsi in quei contorni; con poca fortuna nondimeno, perchè
usciti gli Alemanni con tal bravura li percossero, che vi restò ucciso il
general franzese conte d'Imercourt con alquante centinaia de' suoi;
laonde fu giudicato miglior consiglio il ritirarsi. Verso la metà di
dicembre la fortezza di Monmegliano in Savoia, vinta non dalla forza
ma da un ostinato blocco d'un anno e mezzo, si trovò in fine
obbligata a capitolare con condizioni onorevoli. Per ordine poi del re
Cristianissimo ne furono smantellate tutte le fortificazioni. Così
andavano moltiplicando le perdite e sciagure addosso al duca di
Savoia, il quale non avea cessato di tempestare la corte di Vienna e
le potenze marittime per ottenere gagliardi soccorsi.
Con occhio certamente di compatimento miravano gli alleati
l'infelice positura di questo sì fedele sovrano; e però fu presa la
risoluzione di rispedire in Italia con forze nuove il principe Eugenio,
in cui concorrendo un raro valore e saper militare, e di più la stretta
attinenza di sangue colla real casa di Savoia, si potea perciò da lui
promettere ogni maggiore studio per la causa comune. Ma non gli
furono consegnate forze tali, che potessero per conto alcuno
competere colle franzesi. Ne presentì la venuta il duca di Vandomo;
e per assicurarsi che egli non pensasse alla da tanto tempo bloccata
Mirandola, ordinò che il signor di Lapurà tenente generale degli
ingegneri alla metà d'aprile passasse ad aprir la trincea sotto quella
fortezza. Benchè si trovasse fornito di tenue presidio il conte di
Koningsegg ivi comandante cesareo, pur fece una bella difesa sino al
dì 10 di maggio, in cui si arrendè co' suoi prigioniere di guerra.
Arrivò in questo mentre in Italia il prode principe Eugenio; e da che
ebbe raunato un sufficiente corpo d'armata, costeggiando il lago di
Garda, giunse a Salò. Quivi fu egli indarno trattenuto dalla opposta
nemica armata, perchè seppe aprirsi il passo al piano della
Lombardia, e far poi molti prigioni dei nemici. A Cassano sul fiume
Adda si trovarono poscia a fronte le due nemiche armate nel dì 16 di
agosto, e vennero a giornata campale. Erano maestri di guerra i due
generali, piene di valoroso ardire le truppe di amendue, e però
ciascuna delle parti menò ben le mani, ma con lasciare indecisa la
vittoria, avendo la notte posto fine agli sdegni. Si studiò poi ciascuna
delle parti, secondo il privilegio dei guerrieri, di fare ascendere a più
migliaia la mortalità de' nemici, e tanto meno la propria, di modo che
si intesero da lì a poco intonati due contrarii Te Deum. Forse
maggiore fu la perdita dei Franzesi, ma certo compensata dell'avere i
Tedeschi compianta la morte di più loro generali, oltre a quella del
principe Giuseppe di Lorena. Perchè l'uno e l'altro esercito restò
infievolito da sì copioso salasso, pensò di poi più al riposo che ad
ulteriori militari fatiche, ed altra impresa non succedette pel resto
dell'anno in quelle parti.
Anche nell'alto Reno, alla Mosella e al Brabante non mancarono
azioni militari e sanguinose, e fra queste specialmente rimbombò
l'avere il milord Marlboroug forzate, nel dì 19 di luglio, le linee
franzesi del Brabante, con far prigioni circa mille e cinquecento
Gallispani, fra i quali due generali, e con prendere alquanti cannoni,
bandiere, stendardi e qualche parte del bagaglio. Lo strepito
nondimeno maggiore della guerra fu in Ispagna. Qualche picciolo
acquisto fecero i Portoghesi, assistiti dagli Anglolandi. Assediarono
anche Badaios; ma entrato colà un buon soccorso di Spagna, meglio
si stimò di lasciare in pace quella città. All'incontro la potentissima
flotta combinata degl'Inglesi ed Olandesi con gente da sbarco, e
collo stesso re Carlo III in persona si presentò davanti Barcellona. Al
nome austriaco in gran copia concorsero colà i Catalani armati: dal
che rinvigoriti gli Anglolandi formarono, l'assedio di quella città, e ne
furono direttori il principe di Darmstadt e il milord Peterboroug. Dopo
essersi gli assedianti impadroniti de' forti del Mongiovì, nella quale
impresa quel valoroso principe lasciò la vita, strinsero maggiormente
la città, e finalmente indussero, sul principio d'ottobre, il vicerè
Velasco a capitolare, con accordargli tutti gli onori militari. Ma andò
per terra la capitolazione, perchè prima di effettuarla si mosse a
sedizione il popolo di Barcellona, e v'entrarono gli Austriaci, accolti
con festosi ed incessanti viva. L'acquisto della capitale fu in breve
seguitato da Lerida, Tarragona, Tortosa, Girona ed altri luoghi della
Catalogna. Tumultuarono parimente i popoli del regno di Valenza, e
questa città con Denia, Gandia ed altre terre alzò le bandiere del re
Carlo III. Per quanti sforzi facessero nell'anno presente gli Spagnuoli
per ricuperare Gibilterra con un pertinace assedio, non furono
assistiti dalla fortuna, perchè padroni del mare gli Anglolandi, colà
introdussero di mano in mano quante forze occorrevano per la
difesa. Nel novembre dell'anno presente avvenne una memorabil
rotta del Po sul Mantovano di qua, che rotti gli argini della Secchia e
del Panaro, e seco unite quelle acque, recò incredibili danni a tutta
quella parte del Mantovano, al Mirandolese, a parte del Modenese, e
ad un gran tratto del Ferrarese sino al mare Adriatico. Arrivarono le
acque sino alle mura di Ferrara, atterrarono un'infinità di case e fenili
rurali, colla morte di gran copia di bestie e di non poche persone.
Cristo mdccvi. Indizione xiv.
Anno di Clemente XI papa 7.
Giuseppe imperadore 2.

Se mai fu anno alcuno in Italia, anzi in Europa, fecondo di


avvenimenti militari e di strane metamorfosi, certamente è da dire il
presente. Fra i gran pensieri che agitavano la corte di Francia per
sostenere la monarchia spagnuola lacerata o minacciata in tante
parti dalle armi collegate, uno dei principali si scoprì essere quello di
ultimar la distruzione di Vittorio Amedeo duca di Savoia, principe che
colle sue ardite risoluzioni avea fin qui obbligato il re Cristianissimo
Luigi XIV a mantenere in Italia una guerra che gli costava non pochi
milioni ogni anno. Oppresso questo coraggioso principe, si credea
facile il mettere le sbarre ad ulteriori tentativi della Germania contra
lo Stato di Milano. Già avea per cinquantacinque giorni il marchese di
Caraglio sostenuto il castello di Nizza, benchè flagellato
continuamente da cannoni e mortari del duca di Berwich, quando si
vide ridotto all'estremo, e ridotto a capitolarne la resa con tutti gli
onori militari nel dì 4 di gennaio. Fu poscia condannato quel castello
a vedere uguagliate al suolo tutte le sue fortificazioni. Tanti
preparamenti andava in questo mentre facendo il duca della
Fogliada, che poco ci voleva a comprendere tendenti le sue mire
all'assedio di Torino. Perciò il saggio duca attese a ben premunire
quella capitale e cittadella di quanto potea occorrere in sì fiero
emergente; e da che vide cominciare le offese, con passaporti del
nemico general franzese spedì a Genova la real sua famiglia, ed
anch'egli si mise poi alla larga per maggior sicurezza, riducendosi a
Cuneo e ad altri luoghi fin qui preservati dalle nemiche violenze. Ora
non sì tosto ebbe il suddetto Fogliada ricevuta nuova gente da
Francia con promessa ancora di maggiori rinforzi, che passata la
metà di maggio accostatosi a Torino, diede principio alla
circonvallazione intorno a quella cittadella, dove il prode conte Daun,
lasciato dal duca per governator di Torino insieme col marchese di
Caraglio, avea messo un forte presidio de' suoi Tedeschi. Venuto
poscia il giugno, aprì la trincea sotto quella fortezza, contando dopo
l'acquisto di essa presa anche la città, benchè nè pure ommettesse
le offese contro la città medesima. Orrendo spettacolo era il gran
fuoco dì circa ducento tra cannoni e mortari continuamente impiegati
dai Franzesi a gittar palle, bombe e sassi contro di essa città, e più
contro della cittadella; e un pari trattamento lor faceano i tanti
bronzi e fuochi degli assediati. Nello stesso tempo non lasciò il
Fogliada di marciare con alcune migliaia di fanti e cavalli per voglia di
cogliere, se gli veniva fatto, lo stesso duca di Savoia. Ma egli
vigilante, ora scorrendo in un luogo ed ora in un altro, seppe sempre
schermirsi dai nemici, e dar loro anche qualche percossa, finchè si
ritirò nella valle di Lucerna, dove trovò assai fedeli e arditi alla sua
difesa que' Barbetti. L'essersi perduti in questa diversione i Franzesi,
cagion fu che non progredisse l'assedio di Torino con quel vigore che
richiedeva la positura dei loro affari.
Tornato nella primavera il principe Eugenio sul Trentino, quivi
attese a far massa dei rinforzi a lui promessi, che, secondo il solito
dei Tedeschi, con poca fretta andavano calando dalla Germania. Più
sollecito il duca di Vandomo, dappoichè fu ritornato anch'egli da
Parigi, passata la metà di aprile, uscì in campagna con venticinque
mila combattenti (altri han detto molto meno) a motivo di cacciar dal
piano della Lombardia quelle brigate alemanne che vi erano restate,
e di ristringere le loro speranze fra le montagne delle Alpi. Ben lo
previde il principe Eugenio, e per non perdere l'adito in Italia, ordinò
al generale Reventlau di postarsi fra Calcinato e Lonato con dodici
mila tra fanti e cavalli alla Fossa Seriola, che gli avrebbe servito di
antemurale. Furono malamente eseguiti gli ordini suoi, avendo quel
generale trascurato di ben fortificarsi dalla parte di Lonato. Ora ecco,
nel dì 19 d'aprile, sopraggiugnere il Vandomo dalla parte di
Montechiaro, e poi di Calcinato il quale si spinse contro
l'accampamento nemico. Aspro fu il conflitto, ma in fine i meno
cedettero ai più, e gli Alemanni in rotta si ritirarono il meglio che
poterono a Gavardo. Esaltarono i Franzesi questa vittoria,
pretendendo che restassero prigionieri circa tre mila imperiali, ed
altrettanti freddi sul campo; laddove gli altri contavano solamente
ottocento gli estinti, e circa mille e cinquecento i prigioni e feriti.
Certo è che i Franzesi acquistarono alquanti pezzi di cannone, molte
baudiere e stendardi, e fecero bottino del bagaglio e delle
provvisioni. Dopo questa percossa il principe Eugenio, vedendo
chiusi i passi del Bresciano, andò a poco a poco ritirando dalle rive
del lago di Garda le sue truppe, e a suo tempo improvvisamente
sboccò di nuovo sul Veronese. Gravissimi danni avea patito nel
precedente anno la repubblica veneta sul Bresciano, calpestato dalle
due nemiche armate; maggiori li provò nel presente, perchè il
Vandomo venne colle maggiori sue forze ad accamparsi in vicinanza
di Verona, e stese le sue genti lungo l'Adige, per impedirne il
passaggio agli imperiali. Con pretesto che dai Veneziani si prestasse
o potesse prestare aiuto alle truppe cesaree, alzò dei fortini contro la
città di Verona, non solamente minacciando essa, ma fino il senato
stesso, se non usciva di neutralità. Spinti da sì fatte violenze quei
saggi signori, accrebbero il loro armamento, e risposero di buon
tuono ai Franzesi, senza mai dipartirsi dalla presa risoluzione di non
voler aderire a partito alcuno. Aveano stretta a questo fine, nel dì 12
di gennaio, una lega colle città svizzere di Berna e Zurigo. Intanto
con finte marcie andava il principe Eugenio imbrogliando
l'avvedutezza franzese, finchè, nel dì 6 di luglio, riuscì a un corpo di
sua gente di valicar l'Adige alla Pettorazza, e di afforzarsi
nell'opposta riva: il che aprì l'adito al passaggio di tutta la sua
armata, che, per quanto si figurò la gente, ascendeva a trenta mila
persone, benchè la fama la facesse giugnere sino a quaranta mila.
Curiosa cosa fu il vedere come i dianzi sì baldanzosi Franzesi
battessero una frettolosa ritirata senza mai voler mirare il volto

You might also like