運維少年系列 python and cisco (1)

運維少年系列 python and cisco (1)


預備知識

本系列文章須要各位具備CCNA/HCNA基礎知識(知道命令怎麼敲)python


python

本系列文章須要使用到的python版本爲2.7,模塊爲paramiko。
爲什麼使用python2.7而不是3.x?由於絕大部分系統都自帶了2.7,就這麼簡單~sql

paramiko模塊功能十分強大,最常使用的就是其SSH登陸的功能,使用paramiko實現了SSH登陸以後,還能夠執行命令,實現遠程配置設備。在代碼編寫部分我會向各位簡單的介紹一下每段代碼的做用。shell


系列文章說明

系列文章不會不少(預計2-3篇?),畢竟就一個模塊,從簡單到稍微複雜一點,而後從單點到批量,而後到異常處理,大概的路線就是這樣。文章有些地方可能描述的不許確,請你們多多指教。centos


python and cisco

1) 拓撲圖

  • 使用GNS3作一個簡單的拓撲,將centos橋接GNS3中,使路由器與centos相連。微信

2) 交換機配置

  • 交換機配置ssh,注意密鑰的長度不要使用512,否則登陸會失敗。運維

R3(config)#hostname R3
R3(config)#ip domain name yunwsn.com
R3(config)#crypto key generate rsa
The name for the keys will be: R3.yunwsn.com
Choose the size of the key modulus in the range of 360 to 2048 for your
  General Purpose Keys. Choosing a key modulus greater than 512 may take
  a few minutes.

How many bits in the modulus [512]: 2048
% Generating 512 bit RSA keys, keys will be non-exportable...[OK]
*Mar  1 00:11:52.127: %SSH-5-ENABLED: SSH 2.0 has been enabled
R3(config)#
R2(config)#line vty 0 10
R2(config-line)#transport input ssh
R2(config-line)#login local
R2(config-line)#exit
R1(config)#username yunwsn privilege 15 password 123456
R1(config)#enable password 123456

3) python配置

  • 安裝paramikodom

沒有pip的百度安裝一下吧~python2.7

[root@yunwei ~]# pip install paramiko
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Collecting paramiko
  Using cached https://files.pythonhosted.org/packages/cf/ae/94e70d49044ccc234bfdba20114fa947d7ba6eb68a2e452d89b920e62227/paramiko-2.4.2-py2.py3-none-any.whl
Requirement already satisfied: cryptography>=1.5 in /usr/lib64/python2.7/site-packages (from paramiko) (2.6.1)
Requirement already satisfied: pynacl>=1.0.1 in /usr/lib64/python2.7/site-packages (from paramiko) (1.3.0)
Requirement already satisfied: pyasn1>=0.1.7 in /usr/lib/python2.7/site-packages (from paramiko) (0.4.5)
Requirement already satisfied: bcrypt>=3.1.3 in /usr/lib64/python2.7/site-packages (from paramiko) (3.1.6)
Requirement already satisfied: enum34; python_version < "3" in /usr/lib/python2.7/site-packages (from cryptography>=1.5->paramiko) (1.1.6)
Requirement already satisfied: asn1crypto>=0.21.0 in /usr/lib/python2.7/site-packages (from cryptography>=1.5->paramiko) (0.24.0)
Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/lib64/python2.7/site-packages (from cryptography>=1.5->paramiko) (1.12.3)
Requirement already satisfied: six>=1.4.1 in /usr/lib/python2.7/site-packages (from cryptography>=1.5->paramiko) (1.12.0)
Requirement already satisfied: ipaddress; python_version < "3" in /usr/lib/python2.7/site-packages (from cryptography>=1.5->paramiko) (1.0.22)
Requirement already satisfied: pycparser in /usr/lib/python2.7/site-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.5->paramiko) (2.19)
Installing collected packages: paramiko
Successfully installed paramiko-2.4.2
[root@yunwei ~]# 
  • 代碼編寫ssh

#!/usr/bin/env python
import paramiko   # 導入paramiko模塊
import time       # 導入time模塊,這個後面會用到
host = '192.168.108.254'   # 定義主機IP
user = 'yunwsn'            # 定義登陸的用戶名
passwd = '123456'          # 定義使用的密碼
s = paramiko.SSHClient()   # 實例化,啥意思?請看註釋①
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 請看註釋②
s.connect(host,username=user,password=passwd,look_for_keys=False,allow_agent=False) # 定義登陸的IP、用戶名和密碼
print 'login success.'  # 登陸成功提示
cmd = s.invoke_shell()  # 建立一個交互式的shell,實現多發送條命令
cmd.send("conf t \n")   # 發送命令
time.sleep(1)           # 睡眠1s,特別重要,註釋③
cmd.send("int f0/1 \n")
time.sleep(1)
cmd.send("ip add 1.1.1.2 255.255.255.0 \n")
time.sleep(1)
cmd.send("end \n")
time.sleep(1)
cmd.send("show ip int bri\n ")
time.sleep(1)
output = cmd.recv(65535)  # 接收輸出
print output              # 打印輸出
cmd.close()               # 關閉交互式shell
  • 註釋:ide

    • ①:實例化能夠簡單的理解爲,將paramiko.SSHClient類的全部屬性賦予s。就好比,張三的父親是富一代,那麼屬性就是有錢,而後…嗯,差很少,實例化以後,s可使用原先paramiko.SSHClient()下面全部的辦法,其實也能夠將其理解爲一個別名,給paramiko.SSHClient取個別名叫s

    • ②:在登錄時,有些設備會提示如下內容,須要用戶輸入【yes】才能進行下一步,而使用了這個參數,則不須要輸入yes

    [root@yunwei cisco]# ssh yunwsn@192.168.108.254
    The authenticity of host '192.168.108.254 (192.168.108.254)' can't be established.
    RSA key fingerprint is SHA256:FBFOoRUMkKYCyDbpZKkRiuhCbiYuOX8EuHLUMoN0C/M.
    RSA key fingerprint is MD5:b9:ad:29:24:43:bb:48:8c:58:3e:ce:03:a4:74:e2:cf.
    Are you sure you want to continue connecting (yes/no)? 
  • ③:在個人GNS3中,路由器反應比較慢,好比我輸入了conf t ,他可能過了0.5s才能進入config模式,python的下一條命令int f0/1可能在0.5s的時候就執行了,致使命令執行不成功,因此,我在中間加入了一個睡眠,1s後再執行下個命令,你們在使用的時候能夠修改這個時間,使命令執行時間更加合理。

4) 實現效果

[root@yunwei cisco]# python ywsn_p_c_lab1.py 
login success.

R1#conf t 
Enter configuration commands, one per line.  End with CNTL/Z.
R1(config)#int f0/1 
R1(config-if)#ip add 1.1.1.2 255.255.255.0 
R1(config-if)#end 
R1#show ip int bri
Interface                  IP-Address      OK? Method Status                Protocol
FastEthernet0/0            192.168.108.254 YES manual up                    up      
FastEthernet0/1            1.1.1.2         YES manual up                    down    
FastEthernet0/2            unassigned      YES unset  up                    down    
FastEthernet0/3            unassigned      YES unset  up                    down    
FastEthernet0/4            unassigned      YES unset  up                    down    
FastEthernet0/5            unassigned      YES unset  up                    down    
FastEthernet0/6            unassigned      YES unset  up                    down    
FastEthernet0/7            unassigned      YES unset  up                    down    
FastEthernet0/8            unassigned      YES unset  up                    down    
FastEthernet0/9            unassigned      YES unset  up                    down    
FastEthernet0/10           unassigned      YES unset  up                    down    
FastEthernet0/11           unassigned      YES unset  up                    down    
FastEthernet0/12           unassigned      YES unset  up                    down    
FastEthernet0/13           unassigned      YES unset  up                    down    
FastEthernet0/14           unassigned      YES unset  up                    down    
FastEthernet0/15           unassigned      YES unset  up                    down    
Vlan1                      unassigned      YES unset  up                    down    
R1#
[root@yunwei cisco]

微信公衆號~運維少年

相關文章
相關標籤/搜索