netdevelop

pexpect

1. 发送配置
def ssh_connect(address,port=2605):
#    ssh_command='ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -l %s %s -p %d' % (username, address, port)
    ssh_command='telnet %s %s' % (address,port)
   # print(ssh_command)
    return pexpect.spawn(ssh_command)

def connect(address):
    aa=ssh_connect(address)
    aa.delaybeforesend=0.1
    if aa.expect('Password:')==0:
        aa.sendline('password')


    if aa.expect('BJ-DZC-LLFD>')==0:
        aa.sendline('enable ')


    if aa.expect('BJ-DZC-LLFD#')==0:
        aa.sendline('configure terminal')
        aa.sendline('end')
        aa.sendline('write')
        aa.sendline('exit')

2. 收集配置函数
def commandsend(connection,command):
    jilugroup=[]
    #print time.strftime("%Y-%m-%d %H:%M:%S")
    #connection.timeout=60000
    connection.sendline(command)
    if connection.expect(r'.*>')==0:
    
        #peizhi = (connection.before+connection.after).decode()
        peizhi = (connection.after).decode()
        for line in peizhi.splitlines():
            #print line
            if 'Matched' in line:
                jilu=line.split()[-1]
            elif 'Last 300 seconds input rate' in line:
                jilu=line.split()[5]
            elif 'Last 300 seconds output rate' in line:
                jilu=line.split()[5]
    if 'Eth-Trunk4' in command:
        return int(jilu)*4
    elif 'Eth-Trunk0' in command:
        return int(jilu)
    else:
        return int(jilu)*2

import pexpect
from getpass import getuser
import pexpect,sys
import getpass
from pexpect import EOF,TIMEOUT
import logging

logging.basicConfig(
   level=logging.DEBUG
)
username=input("please input your username:")
password=getpass.getpass('Password:')


def ssh_connect(address):
    ssh_command = 'ssh %s' %(address)
    return pexpect.spawn(ssh_command)
def sendcommand(aa,command):
    if aa.expect(r'\<.*\>|\[.*\]')==0:
        aa.sendline(command)
        result=(aa.before+aa.after).decode()
        print(result)
def connect(address):
    aa = ssh_connect(address)
    aa.delaybeforesend = 0.1
    if aa.expect('Password:') == 0:
        aa.sendline(password)
    if aa.expect(r'<.*>') == 0:
        aa.sendline('screen-length 0 temporary')
    sendcommand(aa,'system-view ')
    for n in range(501,521):
        # print('Creating VLAN ' + str(n))
        # sendcommand(aa,"vlan "+str(n))
        # sendcommand(aa,'name Python_VLAN' + str(n))
        print('deleting vlan '+str(n))
        sendcommand(aa,'undo vlan '+str(n))

    if aa.expect(r'\<.*\>|\[.*\]')==0:
        result=(aa.before+aa.after).decode()
        print(result)

devices=['hw9306a','hw9306b']
for device in devices:
    connect(device)



paramiko

python 2 版本

#!/usr/bin/env python
#coding: utf-8
import paramiko,time
def login(hostname,username,password,port=22):
    ssh=paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    ssh.connect(hostname,port,username,password)
    return ssh
def print_lines(output):
    liuliangcount={}
    for line in output.readlines():
        if '/' in line and 'counter' not in line:
            line=line.strip()
            net=str(line.split()[0])
            count=int(line.split()[1])
            liuliangcount[net]=count
    return liuliangcount    
if __name__=='__main__':

    mx480a={'hostname': '10.10.0.18', 'username': 'usrname', 'password': 'password'}

    ssh=login(mx480a.get("hostname"),mx480a.get("username"),mx480a.get("password"))
    #print "Name                                                Bytes              Packets"
    command=" show firewall filter BJ-CMCC_out_ipv4"
    stdin,stdout,stderr=ssh.exec_command(command)
    time1=time.time()
    liuliangcount1=print_lines(stdout)
    time.sleep(10)
    stdin,stdout,stderr=ssh.exec_command(command)
    time2=time.time()
    liuliangcount2=print_lines(stdout)
    sum=0
    for key in liuliangcount1:
        LiuLiangSuLv=(liuliangcount2[key]-liuliangcount1[key])*8.00/(time2-time1)/1000000
        print "%-20s %-10.3f mbps" %(key,LiuLiangSuLv)
        sum+= LiuLiangSuLv
    print sum
    stdin,stdout,stderr=ssh.exec_command('show interfaces xe-3/2/7 |match "Output rate"')
    for line in stdout.readlines():
        print line.strip()

python 3 版本

import paramiko
import time

ip = 'ip'
username = 'username'
password = 'passowrd'

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 connected to ', ip) 
command = ssh_client.invoke_shell()
command.send('configure\n')
command.send('set interfaces lo0 unit 1 family inet address 3.3.3.3/32\n')
command.send('set routing-instances BJ-TEST interface lo0.1\n')
command.send('show | compare\n')
command.send('commit\n')
command.send('show interfaces lo0 unit 1 | display set\n')
time.sleep(12)
output = command.recv(65535)
print(output.decode('ascii'))

ssh_client.close

netmiko

推荐参考文档:https://zhuanlan.zhihu.com/p/541592293

from netmiko.ssh_dispatcher import platforms
for platform in platforms:
        print(platform)
from netmiko import ConnectHandler
import logging
logging.basicConfig(
    level=logging.DEBUG,
)

if __name__ == '__main__':
#   dev = {
#       'device_type': 'juniper_junos_telnet',
#       'host': 'ip',
#       'username': 'username',
#       'password': 'paaword',
#       'port': 23  # optional, defaults to 22
#   }
#   dev['session_log'] = f"{dev['host']}.log"
#   net_conn = ConnectHandler(**dev)
#   net_conn.config_mode()
#   net_conn.send_config_set(config_commands=['rollback'])
#   net_conn.send_config_set(config_commands=['delete routing-options static route 43.228.180.128/28'])
#   #net_conn.send_config_from_file(config_file='xunda.txt')
#   net_conn.commit()
    dev = {
        #'device_type': 'juniper_junos_telnet',
        'device_type': 'juniper_junos_ssh',
        'host': 'ip',
        'username': 'username',
        'password': 'password',
        #'port': 23  # optional, defaults to 22
        'ssh_config_file': '/root/.ssh/config'
    }
    dev['session_log'] = f"{dev['host']}.log"
 #   dev['session_log'] = dev['host']log+'.log'
    net_conn = ConnectHandler(**dev)
    net_conn.config_mode()
    #net_conn.send_command('delete interface lo0 unit 1',expect_string='.*#')
    net_conn.send_config_set(config_commands=['set interfaces lo0 unit 1','set interfaces lo0 unit 1 family inet address 2.2.2.2/32','set routing-instances BJ-TEST interface lo0.1'])
    #net_conn.send_config_set(config_commands=['set routing-options static route 43.228.180.128/28 next-hop 10.3.254.10'])
 #   net_conn.send_config_from_file(config_file='geaiqing')
 #   net_conn.commit()
 output=net_conn.send_command(command)
 print(output)

juniper 重启参考

from netmiko import ConnectHandler
import time

# 定义设备信息
device = {
    'device_type': 'juniper_junos',
    'host': 'xxxxx,
    'username': 'xxxx',
    'password': 'xxxxxx',
}

# 连接到设备
net_connect = ConnectHandler(**device)

# 发送重启命令
print("Sending reboot command...")
output = net_connect.send_command_timing("request system reboot both-routing-engines")
print(output)
# 确认是否继续
if "yes" in output:
    output += net_connect.send_command_timing("yes")
    print("Rebooting device...")
    time.sleep(5)  # 等待设备重启,你可以根据需要调整此时间
else:
    print("Failed to send reboot command.")

# 断开连接
net_connect.disconnect()
posted @ 2023-08-24 10:35  lifei888  阅读(33)  评论(0)    收藏  举报