Python 네트워크 자동화 eNSP 실현

1.Paramiko 를 사용 하여 단일 교환기 에 로그 인
실험 토폴로지
운채 교 는 본 기계 의 순환 인 터 페 이 스 를 받 았 다.192.168.1.1/24
삼층 교환기 IP:192.168.1.2/24
在这里插入图片描述
실험 요구
Python Paramiko 모듈 을 사용 하여 SSH 로그 인 단일 교환기(192.168.56.5.2/24)를 실현 하고 LoopBack 0 주소:1.1.1.1/32 를 설정 합 니 다.설정 이 완료 되면 종료 저장.
실험 절 차 는 교환기 관리 주 소 를 설정 하고 호스트 가상 네트워크 카드 와 의 연결 성 을 테스트 합 니 다.

[Huawei]vlan 10
[Huawei]int vlan 10
[Huawei-Vlanif10]ip add 192.168.1.2 24
[Huawei-GigabitEthernet0/0/1]port link-type access 
[Huawei-GigabitEthernet0/0/1]port default vlan 10
在这里插入图片描述
在这里插入图片描述
3 층 교환 기 를 설정 하여 SSH 서버 를 열 고 SSH 계 정 비밀 번 호 를 설정 합 니 다.

[Huawei]user-interface vty 0 4
[Huawei-ui-vty0-4]authentication-mode aaa
[Huawei-ui-vty0-4]protocol inbound ssh
[Huawei-aaa]local-user python password cipher 123
[Huawei-aaa]local-user python privilege level 3
[Huawei-aaa]local-user python service-type ssh 
[Huawei]stelnet server enable 
[Huawei]ssh authentication-type default password 
파 이 썬 코드

import paramiko
import time

ip = '192.168.56.2'
username = 'python'
password = '123'

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) //     ,Paramiko        SSH public keys,                 public keys。
ssh_client.connect(hostname=ip, username=username, password=password, look_for_keys=False)
print('Successfully connect to ' + ip)

commend = ssh_client.invoke_shell()
commend.send('sys
') commend.send('interface LoopBack 0
') commend.send('ip add 1.1.1.1 255.255.255.255
') commend.send('return
') commend.send('save
') commend.send('y
') time.sleep(3) // 3 , output = commend.recv(65535) // script , assign output print(output.decode("ascii")) ssh_client.close()
실행 결과 보기
在这里插入图片描述
교환기 에서 보기
在这里插入图片描述
교환기 에서 debuggiing ip packet 에서 로 그 를 볼 수 있 습 니 다.
2.연속 서브 넷 교환기 에 Paramiko 로 로그 인
실험 토폴로지
연속 서브 넷 3 층 교환기:관리 주소 192.168.1.2/24 to 192.168.1.5/24
在这里插入图片描述
실험 요구
각 교환기 에 로그 인하 여 vlan 11 to 15 를 설정 하고 설정 을 저장 하고 종료 합 니 다.
실험 절차
관리 포트 IP 주 소 를 설정 하고 SSH 서버 로그 인 이름과 비밀번호 등 을 설정 합 니 다.
python 코드

import paramiko
import time

#import getpass
#username = input('Username: ')
#password = getpass.getpass('Password: ') //pycharm         ,            

username = 'python'
password = '123'

for i in range(2, 6):
    ip = '192.168.1.' + str(i)
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(hostname=ip, username=username, password=password, look_for_keys=False)
    command = ssh_client.invoke_shell()
    print('Successfully connect to ' + ip)
    command.send('sys
') for j in range(11, 16): print(' VLAN: ' + str(j)) command.send('vlan ' + str(j) + '
') time.sleep(1) command.send('return
') command.send('save
') command.send('y
') time.sleep(2) output = command.recv(65535).decode('ascii') print(output) ssh_client.close()
실행 결과
在这里插入图片描述
在这里插入图片描述
3.Paramiko 로그 인 불 연속 서브 넷 교환기
실험 토폴로지
교환기 LSW 5 의 관리 인터페이스 ip 을 192.168.1.6/24 로 변경 하여 교환기 ip 가 같은 네트워크 에 없 도록 합 니 다.
在这里插入图片描述
실험 요구
Paramiko 를 사용 하여 네 대의 ip 불 연속 교환기 에 로그 인하 고 vlan 11 to 15 를 설정 합 니 다.
실험 절차
텍스트 문 서 를 만 듭 니 다.설정 해 야 할 교환기 의 ip 주 소 를 기록 합 니 다.데스크 톱 에서 ip.txt 라 는 문 서 를 만 들 었 습 니 다.
在这里插入图片描述
open 함 수 를 사용 하여 파일 을 열 고 조작 하여 불 연속 서브 네트워크 호출 을 실현 합 니 다.

import paramiko
import time

username = 'python'
password = '123'

f = open('C:/Users/DELL/Desktop/ip.txt', 'r')
for line in f.readlines():
    ip = line.strip()
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(hostname=ip, username=username, password=password)
    print('Successfully connect to ', ip)
    command = ssh_client.invoke_shell()
    command.send('sys
') command.send('vlan batch 11 to 15
') time.sleep(2) command.send('return
') command.send('save
') command.send('y
') time.sleep(2) output = command.recv(65535).decode('ascii') print(output) f.close() ssh_client.close()
실행 결과 보기
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
4.sys.argv[]유연 한 스 크 립 트 호출 에 필요 한 파일
실험 토폴로지
1.2 와 1.3 을 한 조로 가정 하고 1.4 와 1.6 을 한 조로 한다.
在这里插入图片描述
실험 요구
동시에 서로 다른 모델 의 장치 설정 을 수정 하여 SW1/3 에 vlan 11 to 15,SW4/5 에 vlan 16 to 20 을 설정 합 니 다.
실험 절차
ip1.txt,command1.txt 라 는 파일 을 만 들 고 1 조 의 ip 와 진행 할 설정 을 저장 합 니 다.
在这里插入图片描述
ip2.txt,command2.txt 파일 두 개 를 만 들 고 2 조 의 ip 와 진행 할 설정 을 저장 합 니 다.
在这里插入图片描述
在这里插入图片描述
python 코드

import paramiko
import time
import sys

username = 'python'
password = '123'

ip_file = sys.argv[1]
cmd_file = sys.argv[2]

iplist = open(ip_file)
for line in iplist.readlines():
    ip = line.strip()
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(hostname=ip, username=username, password=password)
    print('Successfully connect to ', ip)
    command = ssh_client.invoke_shell()
    cmdlist = open(cmd_file, 'r')
    cmdlist.seek(0)
    for line in cmdlist.readlines():
        command.send(line + '
') time.sleep(5) cmdlist.close() output = command.recv(65535) print(output) iplist.close() ssh_client.close()
실행 결 과 를 보기(pycharm 은 argv 를 사용 할 수 없고 cmd 에서 사용 할 수 없습니다)
在这里插入图片描述
5.SSH 연결 실패 처리

import paramiko
import time
import sys
import socket
import getpass

username = input('Username: ')
password = getpass.getpass('Password: ')
ip_file = sys.argv[1]
cmd_file = sys.argv[2]

switch_with_authentication_issue = []
switch_not_reachable = []

iplist = open(ip_file, 'r')
for line in iplist.readlines():
    try:
        ip = line.strip()
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=ip, username=username, password=password,look_for_keys=False)
        print('Successfully connect to ' + ip)
        command = ssh_client.invoke_shell()
        cmdlist = open(cmd_file, 'r')
        cmdlist.seek(0)
        for cmd in cmdlist.readlines():
            command.send(cmd + '
') time.sleep(1) cmdlist.close() output = command.recv(65535) print(output.decode("ascii")) except paramiko.ssh_exception.AuthenticationException: print('User authentication failed for ' + ip + '.') switch_with_authentication_issue.append(ip) except TimeoutError: switch_not_reachable.append(ip) iplist.close() ssh_client.close() print('
User authentication failed for below switches: ') for i in switch_with_authentication_issue: print(i) print('
Below switchs are not reachable: ') for i in switch_not_reachable: print(i)
파 이 썬 의 네트워크 자동화 eNSP 실현 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 파 이 썬 네트워크 자동화 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!

좋은 웹페이지 즐겨찾기