通过Python给通信设备下发配置-代码

pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple

import paramiko
import time
from pysnmp.hlapi import *
from ncclient import manager
from ncclient.xml_ import to_ele

def ssh_Commd():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname="192.168.56.20",port=22,username="huawei**", password="Admin***")
    print("====ssh成功====\n", ssh)
    vty = ssh.invoke_shell()
    print("====vty成功====\n", vty)
    f = open("ssh配置文件.txt","r",encoding="utf-8")
    vty.send("screen-length 0 temporary\n".encode('utf-8'))
    time.sleep(1)
    lines = f.readlines()
    for line in lines:
        vty.send((line).encode('utf-8'))
        time.sleep(1)
    time.sleep(1)
    res = vty.recv(65536).decode('utf-8')
    print(res)
    ssh.close()


def sftp_UP_Commd(hostip,path):
    trans = paramiko.Transport(hostip,22)
    trans.connect(username="huawei", password="Admin@123")
    sftp = paramiko.SFTPClient.from_transport(trans)
    print("====sftp====\n", sftp)
    local = path
    remote = path
    sftp.put(local,remote)
    print("====上传成功====")
    sftp.close()

def sftp_down_Commd(hostip):
    trans = paramiko.Transport(hostip,22)
    trans.connect(username="huawei***", password="Admin***")
    sftp = paramiko.SFTPClient.from_transport(trans)
    remote = "config.cfg"
    local = "vrpcfg.cfg"
    sftp.get(remote,local)
    print("===下载成功====")
    sftp.close()


def snmp_Commd(hostip):
    getinform=(getCmd(
        SnmpEngine(),
        UsmUserData(
            userName="admin123",
            authKey ="Huawei@1234",
            privKey="Huawei@1234",
            authProtocol = usmHMACSHAAuthProtocol,
            privProtocol = usmAesCfb128Protocol
        ),
        UdpTransportTarget((hostip,161)),
        ContextData(),
        ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0')),  #hwEntityCpuUsage
    ))
    res =next(getinform)[-1][-1]
    result = str(res).split("=")[1].strip()
    print("===snmp res====\n", result)
    svaeFile(result ,"snmpRes.txt")

def Netconf_Commd(hostip):
    return manager.connect(
        host=hostip,
        port=830,
        username="huawei**",
        password="Admin***",
        look_for_keys=False,
        allow_agent=False,
        hostkey_verify=False,
        device_params={'name':'huawei'},
    )


def readRes():
    f = open("vrpcfg.cfg","r",encoding="utf-8")
    lines = f.readlines()
    for line in lines:
        if(line.find("ntp")>0):
            print("=======使能结果=====",line)

def saveFile(result,path):
    print(result)
    resline = str(result).split('\\r\\n')
    print(resline)
    f = open(path, "w", encoding="utf-8")
    for res in resline:
        f.write(res+'\n')
    f.close()


if __name__ == '__main__':
    path1 = "ssh1.txt"
    path2 = "ssh2.txt"
    path3 = "SNMPv3"
    path4 = "D:/PycharmProjects/DemoProject/.venv/command.txt"

    hostip = "192.168.20.254"
    hostip1 = "192.168.56.101"
    #1
    ssh_Commd(hostip, path2)

    #3
    #snmp_Commd("192.168.20.254")

    #5
    CONFIG="""
    <edit-config>
    <target>
      <running/>
    </target>
    <default-operation>merge</default-operation>
    <error-option>rollback-on-error</error-option>
    <config>
      <ntp xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
        <ntpSrvrDsblCfgs>
          <ntpSrvrDsblCfg operation="merge">
            <addrFamily>IPv4</addrFamily>
          </ntpSrvrDsblCfg>
        </ntpSrvrDsblCfgs>
      </ntp>
    </config>
  </edit-config>
    """
    mes = Netconf_Commd(hostip)
    content = to_ele(CONFIG)
    res = mes.rpc(content)
    print("=====netconf res=====",res)
    mes.close_session()


    sftp_down_Commd(hostip)

抓包

from scapy.all import *
from scapy.layers.inet import *
import pyshark
import numpy as np

pkt = IP(src="172.31.1.***",dst="153.3.238.110")/ICMP()
res = sr1(pkt)
print("==========res.summary()==============",res.summary())
print("==========res.show()=================",res.show())
res = sr1(pkt)
wrpcap("wireshark01.cap",pkt)

# 初始化一些用于存储数据的列表
timestamps = []
source_ips = []
destination_ips = []
pcap_file = 'wireshark01.cap'
capture = pyshark.FileCapture(pcap_file)
print("========capture===========",capture)
# 遍历pcap中的每个packet
for packet in capture:
    # 获取时间戳
    timestamp = float(packet.sniff_timestamp)
    timestamps.append(timestamp)
    print(timestamp)

    # 获取源IP和目的IP
    source_ip = packet.ip.src
    print("源IP",packet.ip.src,packet.ip.proto)
    destination_ip = packet.ip.ds
    print("目标IP", packet.ip.dst)
    source_ips.append(source_ip)
    destination_ips.append(destination_ip)

print(conf.ifaces)
def cell(pkt):
    print(pkt.summary)
sniff(filter="icmp and host 172.31.1.***", iface = 'Intel(R) Dual Band Wireless-AC 8265', prn=cell,count = 3 )

# 将列表转换为NumPy数组
timestamps = np.array(timestamps)
print("timestamps", np.array(timestamps))
source_ips = np.array(source_ips)
print("数组形IP地址", np.array(source_ips))
destination_ips = np.array(destination_ips)
print("数组形IP地址", np.array(destination_ips))
# 现在你可以使用NumPy对数据进行分析了,例如计算平均时间戳
average_timestamp = np.mean(timestamps)
print(f"Average Timestamp: {average_timestamp}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值