Python Tips and Tricks_第1张图片Python Tips and Tricks_第2张图片
1.  Install Python into Windows

1.1 Download Latest Python 2 file from https://www.python.org/downloads/windows/

  • Latest Python 3 Release – Python 3.7.0
  • Latest Python 2 Release – Python 2.7.15

1.2 Double Click download python-2.7.15.exe file to install it.

1.3 Run Python
By Default, it will be installed at c:\Python27 folder


C:\Users\John>cd \

C:\>cd Python27

C:\Python27>python --version
Python 2.7.15

C:\Python27>python
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:22:17) [MSC v.1500 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 


1.4 Install paramiko module
Paramiko is a Python (2.7, 3.4+) implementation of the SSHv2 protocol [1], providing both client and server functionality. While it leverages a Python C extension for low level cryptography (Cryptography), Paramiko itself is a pure Python interface around SSH networking concepts.

  • Install Python 2.7.11
  • Download and install pycrypto win-amd64-py2.7.exe
  • Now open a command prompt. If you have installed python at the following location:

c:\Python27 then change directory and go to Scripts directory.

pip install paramiko

  • Now Test with the following command:

import paramiko

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install paramiko
Collecting paramiko
  Downloading https://files.pythonhosted.org/packages/3e/db/cb7b6656e0e7387637ce
850689084dc0b94b44df31cc52e5fc5c2c4fd2c1/paramiko-2.4.1-py2.py3-none-any.whl (19
4kB)
    100% |################################| 194kB 1.2MB/s
Collecting bcrypt>=3.1.3 (from paramiko)
  Downloading https://files.pythonhosted.org/packages/4c/49/26ea2bf908e8d4250023
e3b104e01b97ce48d6a7687c589c15d0a9f57fda/bcrypt-3.1.4-cp27-cp27m-win32.whl
Collecting pyasn1>=0.1.7 (from paramiko)
  Downloading https://files.pythonhosted.org/packages/d1/a1/7790cc85db38daa874f6
a2e6308131b9953feb1367f2ae2d1123bb93a9f5/pyasn1-0.4.4-py2.py3-none-any.whl (72kB
)
    100% |################################| 81kB 1.6MB/s
Collecting pynacl>=1.0.1 (from paramiko)
  Downloading https://files.pythonhosted.org/packages/f9/cc/0f1eb2ff37aa1b89cdc0
6c1721d057ca648efe7f51a4b67c29cee9db9f33/PyNaCl-1.2.1-cp27-cp27m-win32.whl (162k
B)
    100% |################################| 163kB 1.3MB/s
Collecting cryptography>=1.5 (from paramiko)
  Downloading https://files.pythonhosted.org/packages/24/fc/4c5459b470068692fadd
135080bbec1ee5b9e9de27cfd04f5a0d4b7a2400/cryptography-2.3.1-cp27-cp27m-win32.whl
 (1.1MB)
    100% |################################| 1.1MB 716kB/s
Collecting six>=1.4.1 (from bcrypt>=3.1.3->paramiko)
  Downloading https://files.pythonhosted.org/packages/67/4b/141a581104b1f6397bfa
78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl
Collecting cffi>=1.1 (from bcrypt>=3.1.3->paramiko)
  Downloading https://files.pythonhosted.org/packages/3a/84/9d1bf29b212853087318
696c38241a3af65b33ea2edaabad11f26826ecf4/cffi-1.11.5-cp27-cp27m-win32.whl (153kB
)
    100% |################################| 153kB 1.2MB/s
Collecting enum34; python_version < "3" (from cryptography>=1.5->paramiko)
  Downloading https://files.pythonhosted.org/packages/c5/db/e56e6b4bbac7c4a06de1
c50de6fe1ef3810018ae11732a50f15f62c7d050/enum34-1.1.6-py2-none-any.whl
Collecting idna>=2.1 (from cryptography>=1.5->paramiko)
  Downloading https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1
af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl (58kB)
    100% |################################| 61kB 1.7MB/s
Collecting asn1crypto>=0.21.0 (from cryptography>=1.5->paramiko)
  Downloading https://files.pythonhosted.org/packages/ea/cd/35485615f45f30a51057
6f1a56d1e0a7ad7bd8ab5ed7cdc600ef7cd06222/asn1crypto-0.24.0-py2.py3-none-any.whl
(101kB)
    100% |################################| 102kB 1.7MB/s
Collecting ipaddress; python_version < "3" (from cryptography>=1.5->paramiko)
  Downloading https://files.pythonhosted.org/packages/fc/d0/7fc3a811e011d4b388be
48a0e381db8d990042df54aa4ef4599a31d39853/ipaddress-1.0.22-py2.py3-none-any.whl
Collecting pycparser (from cffi>=1.1->bcrypt>=3.1.3->paramiko)
  Downloading https://files.pythonhosted.org/packages/8c/2d/aad7f16146f4197a11f8
e91fb81df177adcc2073d36a17b1491fd09df6ed/pycparser-2.18.tar.gz (245kB)
    100% |################################| 256kB 1.2MB/s
Installing collected packages: six, pycparser, cffi, bcrypt, pyasn1, pynacl, enu
m34, idna, asn1crypto, ipaddress, cryptography, paramiko
  Running setup.py install for pycparser ... done
Successfully installed asn1crypto-0.24.0 bcrypt-3.1.4 cffi-1.11.5 cryptography-2
.3.1 enum34-1.1.6 idna-2.7 ipaddress-1.0.22 paramiko-2.4.1 pyasn1-0.4.4 pycparse
r-2.18 pynacl-1.2.1 six-1.11.0
You are using pip version 9.0.3, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.

C:\Python27\Scripts>cd ..

C:\Python27>python
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:22:17) [MSC v.1500 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> exit()

C:\Python27>


2. Install Python 2.7 / 3.0 on AWS EC2 Instance


[[email protected] pexpect-2.3]$ python --version
Python 2.7.14



[[email protected] pexpect-2.3]$ sudo yum install python
Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main                                                                             | 2.1 kB  00:00:00
amzn-updates                                                                          | 2.5 kB  00:00:00
Resolving Dependencies
--> Running transaction check
---> Package python26.x86_64 0:2.6.9-2.89.amzn1 will be installed
--> Processing Dependency: libpython2.6.so.1.0()(64bit) for package: python26-2.6.9-2.89.amzn1.x86_64
--> Running transaction check
---> Package python26-libs.x86_64 0:2.6.9-2.89.amzn1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================
 Package                    Arch                Version                         Repository              Size
=============================================================================================================
Installing:
 python26                   x86_64              2.6.9-2.89.amzn1                amzn-main              5.8 M
Installing for dependencies:
 python26-libs              x86_64              2.6.9-2.89.amzn1                amzn-main              697 k

Transaction Summary
=============================================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 6.4 M
Installed size: 21 M
Is this ok [y/d/N]: ^Cn
Exiting on user command
Your transaction was saved, rerun it with:
 yum load-transaction /tmp/yum_save_tx.2018-06-21.18-42.2ccPPk.yumtx

[[email protected] pexpect-2.3]$ python --version
Python 2.7.14
[[email protected] pexpect-2.3]$ sudo apt-get install python3
sudo: apt-get: command not found
[[email protected] pexpect-2.3]$ sudo yum install python
Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main                                                                             | 2.1 kB  00:00:00
amzn-updates                                                                          | 2.5 kB  00:00:00
Package python26-2.6.9-2.89.amzn1.x86_64 already installed and latest version
Nothing to do

[[email protected] pexpect-2.3]$ sudo yum list | grep python3
mod24_wsgi-python34.x86_64            3.5-1.25.amzn1                amzn-updates
mod24_wsgi-python35.x86_64            3.5-1.25.amzn1                amzn-updates
mod24_wsgi-python36.x86_64            3.5-1.25.amzn1                amzn-updates
python34.x86_64                       3.4.8-1.39.amzn1              amzn-updates
python34-devel.x86_64                 3.4.8-1.39.amzn1              amzn-updates
python34-docs.noarch                  3.4.3-1.23.amzn1              amzn-main
python34-libs.i686                    3.4.8-1.39.amzn1              amzn-updates
python34-libs.x86_64                  3.4.8-1.39.amzn1              amzn-updates
python34-pip.noarch                   9.0.3-1.26.amzn1              amzn-updates
python34-setuptools.noarch            36.2.7-1.33.amzn1             amzn-main
[[email protected] pexpect-2.3]$ sudo yum install python34
Loaded plugins: priorities, update-motd, upgrade-helper
Resolving Dependencies
--> Running transaction check
---> Package python34.x86_64 0:3.4.8-1.39.amzn1 will be installed
--> Processing Dependency: python34-libs(x86-64) = 3.4.8-1.39.amzn1 for package: python34-3.4.8-1.39.amzn1.x86_64
--> Processing Dependency: libpython3.4m.so.1.0()(64bit) for package: python34-3.4.8-1.39.amzn1.x86_64
--> Running transaction check
---> Package python34-libs.x86_64 0:3.4.8-1.39.amzn1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================
 Package                   Arch               Version                         Repository                Size
=============================================================================================================
Installing:
 python34                  x86_64             3.4.8-1.39.amzn1                amzn-updates              54 k
Installing for dependencies:
 python34-libs             x86_64             3.4.8-1.39.amzn1                amzn-updates             9.8 M

Transaction Summary
=============================================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 9.8 M
Installed size: 27 M
Is this ok [y/d/N]: y
Downloading packages:
(1/2): python34-3.4.8-1.39.amzn1.x86_64.rpm                                           |  54 kB  00:00:00
(2/2): python34-libs-3.4.8-1.39.amzn1.x86_64.rpm                                      | 9.8 MB  00:00:00
-------------------------------------------------------------------------------------------------------------
Total                                                                         20 MB/s | 9.8 MB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : python34-3.4.8-1.39.amzn1.x86_64                                                          1/2
  Installing : python34-libs-3.4.8-1.39.amzn1.x86_64                                                     2/2
  Verifying  : python34-libs-3.4.8-1.39.amzn1.x86_64                                                     1/2
  Verifying  : python34-3.4.8-1.39.amzn1.x86_64                                                          2/2

Installed:
  python34.x86_64 0:3.4.8-1.39.amzn1

Dependency Installed:
  python34-libs.x86_64 0:3.4.8-1.39.amzn1

Complete!
[[email protected] pexpect-2.3]$
[[email protected] pexpect-2.3]$ python --version
Python 2.7.14
[[email protected] pexpect-2.3]$ python3 --version
Python 3.4.8
[[email protected] pexpect-2.3]$

[[email protected] ~]$ python3
Python 3.4.8 (default, Apr 25 2018, 23:50:36)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World")
Hello World
>>>


[[email protected] ~]$ sudo yum update
Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main                                                                                                                                        | 2.1 kB  00:00:00
amzn-updates                                                                                                                                     | 2.5 kB  00:00:00
Resolving Dependencies
--> Running transaction check
---> Package cloud-init.noarch 0:0.7.6-2.15.amzn1 will be updated
---> Package cloud-init.noarch 0:0.7.6-2.16.amzn1 will be an update
---> Package dhclient.x86_64 12:4.1.1-53.P1.27.amzn1 will be updated
---> Package dhclient.x86_64 12:4.1.1-53.P1.28.amzn1 will be an update
---> Package dhcp-common.x86_64 12:4.1.1-53.P1.27.amzn1 will be updated
---> Package dhcp-common.x86_64 12:4.1.1-53.P1.28.amzn1 will be an update
---> Package gnupg2.x86_64 0:2.0.28-1.30.amzn1 will be updated
---> Package gnupg2.x86_64 0:2.0.28-2.31.amzn1 will be an update
---> Package kernel.x86_64 0:4.14.51-60.38.amzn1 will be installed
---> Package kernel-tools.x86_64 0:4.14.47-56.37.amzn1 will be updated
---> Package kernel-tools.x86_64 0:4.14.51-60.38.amzn1 will be an update
---> Package ntp.x86_64 0:4.2.6p5-44.36.amzn1 will be updated
---> Package ntp.x86_64 0:4.2.8p11-2.38.amzn1 will be an update
---> Package ntpdate.x86_64 0:4.2.6p5-44.36.amzn1 will be updated
---> Package ntpdate.x86_64 0:4.2.8p11-2.38.amzn1 will be an update
---> Package openssh.x86_64 0:7.4p1-11.68.amzn1 will be updated
---> Package openssh.x86_64 0:7.4p1-16.69.amzn1 will be an update
---> Package openssh-clients.x86_64 0:7.4p1-11.68.amzn1 will be updated
---> Package openssh-clients.x86_64 0:7.4p1-16.69.amzn1 will be an update
---> Package openssh-server.x86_64 0:7.4p1-11.68.amzn1 will be updated
---> Package openssh-server.x86_64 0:7.4p1-16.69.amzn1 will be an update
---> Package openssl.x86_64 1:1.0.2k-8.107.amzn1 will be updated
---> Package openssl.x86_64 1:1.0.2k-12.109.amzn1 will be an update
---> Package rpcbind.x86_64 0:0.2.0-13.9.amzn1 will be updated
---> Package rpcbind.x86_64 0:0.2.0-13.10.amzn1 will be an update
---> Package wget.x86_64 0:1.18-3.28.amzn1 will be updated
---> Package wget.x86_64 0:1.18-4.29.amzn1 will be an update
--> Finished Dependency Resolution

Dependencies Resolved

========================================================================================================================================================================
 Package                                  Arch                            Version                                           Repository                             Size
========================================================================================================================================================================
Installing:
 kernel                                   x86_64                          4.14.51-60.38.amzn1                               amzn-updates                           21 M
Updating:
 cloud-init                               noarch                          0.7.6-2.16.amzn1                                  amzn-updates                          422 k
 dhclient                                 x86_64                          12:4.1.1-53.P1.28.amzn1                           amzn-updates                          346 k
 dhcp-common                              x86_64                          12:4.1.1-53.P1.28.amzn1                           amzn-updates                          149 k
 gnupg2                                   x86_64                          2.0.28-2.31.amzn1                                 amzn-updates                          2.6 M
 kernel-tools                             x86_64                          4.14.51-60.38.amzn1                               amzn-updates                          124 k
 ntp                                      x86_64                          4.2.8p11-2.38.amzn1                               amzn-updates                          1.0 M
 ntpdate                                  x86_64                          4.2.8p11-2.38.amzn1                               amzn-updates                           88 k
 openssh                                  x86_64                          7.4p1-16.69.amzn1                                 amzn-updates                          639 k
 openssh-clients                          x86_64                          7.4p1-16.69.amzn1                                 amzn-updates                          1.1 M
 openssh-server                           x86_64                          7.4p1-16.69.amzn1                                 amzn-updates                          511 k
 openssl                                  x86_64                          1:1.0.2k-12.109.amzn1                             amzn-updates                          1.8 M
 rpcbind                                  x86_64                          0.2.0-13.10.amzn1                                 amzn-updates                           56 k
 wget                                     x86_64                          1.18-4.29.amzn1                                   amzn-updates                          981 k

Transaction Summary
========================================================================================================================================================================
Install   1 Package
Upgrade  13 Packages

Total download size: 31 M
Is this ok [y/d/N]: y


3. Use Python Pexpect module to do SSH/FTP connection

[[email protected] ~]$ wget http://pexpect.sourceforge.net/pexpect-2.3.tar.gz
--2018-06-21 15:38:31--  http://pexpect.sourceforge.net/pexpect-2.3.tar.gz
Resolving pexpect.sourceforge.net (pexpect.sourceforge.net)... 216.105.38.10
Connecting to pexpect.sourceforge.net (pexpect.sourceforge.net)|216.105.38.10|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 150868 (147K) [application/x-gzip]
Saving to: ‘pexpect-2.3.tar.gz’

pexpect-2.3.tar.gz          100%[========================================>] 147.33K   680KB/s    in 0.2s

2018-06-21 15:38:31 (680 KB/s) - ‘pexpect-2.3.tar.gz’ saved [150868/150868]

[[email protected] ~]$ tar xzf pexpect-2.3.tar.gz
[[email protected] ~]$ cd pexpect-2.3
[[email protected] pexpect-2.3]$ sudo python ./setup.py install
running install
running build
running build_py
creating build
creating build/lib
copying pexpect.py -> build/lib
copying pxssh.py -> build/lib
copying fdpexpect.py -> build/lib
copying FSM.py -> build/lib
copying screen.py -> build/lib
copying ANSI.py -> build/lib
running install_lib
copying build/lib/FSM.py -> /usr/local/lib/python2.7/site-packages
copying build/lib/fdpexpect.py -> /usr/local/lib/python2.7/site-packages
copying build/lib/pexpect.py -> /usr/local/lib/python2.7/site-packages
copying build/lib/ANSI.py -> /usr/local/lib/python2.7/site-packages
copying build/lib/pxssh.py -> /usr/local/lib/python2.7/site-packages
copying build/lib/screen.py -> /usr/local/lib/python2.7/site-packages
byte-compiling /usr/local/lib/python2.7/site-packages/FSM.py to FSM.pyc
byte-compiling /usr/local/lib/python2.7/site-packages/fdpexpect.py to fdpexpect.pyc
byte-compiling /usr/local/lib/python2.7/site-packages/pexpect.py to pexpect.pyc
byte-compiling /usr/local/lib/python2.7/site-packages/ANSI.py to ANSI.pyc
byte-compiling /usr/local/lib/python2.7/site-packages/pxssh.py to pxssh.pyc
byte-compiling /usr/local/lib/python2.7/site-packages/screen.py to screen.pyc
running install_egg_info
Writing /usr/local/lib/python2.7/site-packages/pexpect-2.3.egg-info


[[email protected] pexpect-2.3]$ sudo yum install pexpect.noarch
Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main                                                                             | 2.1 kB  00:00:00
amzn-updates                                                                          | 2.5 kB  00:00:00
No package pexpect.noarch available.
Error: Nothing to do
[[email protected] pexpect-2.3]$ sudo apt-get install python-pexpect
sudo: apt-get: command not found
[[email protected] pexpect-2.3]$ python
Python 2.7.14 (default, May  2 2018, 18:31:34)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pexpect


4. Python Script to Execute Cisco Commands on Cisco IOS devices

C:\Python27>type cisco.py
import paramiko
from getpass import getpass
import time
import datetime
import sys

ip = raw_input("Please enter your IP address: ")
username = "admin"
password = "[email protected]"

f = open('NewdayTest.txt', 'a')
old_stdout = sys.stdout
sys.stdout = f
remote_conn_pre=paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(ip, port=22, username=username,  
                        password=password,
                        look_for_keys=False, allow_agent=False)

remote_conn = remote_conn_pre.invoke_shell()
output = remote_conn.recv(65535)
print('\n\n\n##############################################################\n')
print (datetime.datetime.now())
print('\n##############################################################\n')
print (output)

remote_conn.send("config t\n")
time.sleep(.5)
output = remote_conn.recv(65535)
print (output)

remote_conn.send("file prompt quiet\n")
time.sleep(.5)
output = remote_conn.recv(65535)
print (output)

remote_conn.send("end\n")
time.sleep(.5)
output = remote_conn.recv(65535)
print (output)

remote_conn.send("copy running-config tftp://192.168.2.5/\n")
time.sleep(2)
stdout = remote_conn.recv(65535)
print (stdout)

remote_conn.send("config t\n")
time.sleep(.5)
output = remote_conn.recv(65535)
print (output)

remote_conn.send("file prompt alert\n")
time.sleep(.5)
output = remote_conn.recv(65535)
print (output)

remote_conn.send("exit\n")
time.sleep(.5)
output = remote_conn.recv(65535)
print (output)

f.close()

C:\Python27>python cisco.py
 
   
C:\Python27>type Newdaytest.txt


##############################################################
2018-08-24 12:38:42.178000
##############################################################

****************************************************************
* This is a private computing facility. *
* Unauthorized use of this device is strictly prohibited. *
* Violators will be prosecuted to the maximum extent possible. *
* *
* TACACS+ Authentication and Accounting are in place. *
* All actions/commands are monitored and recorded. *
* By using the network you expressly consent to such *
* monitoring and recording. *
****************************************************************

SW-FW-MGMT1#config t
Enter configuration commands, one per line. End with CNTL/Z.
SW-FW-MGMT1(config)#
file prompt quiet
SW-FW-MGMT1(config)#
end
SW-FW-MGMT1#
copy running-config tftp://192.168.154.5/
.
.
.