首页 > 编程语言 >The Network Program Log One(网络自动编程)

The Network Program Log One(网络自动编程)

时间:2024-10-11 11:49:32浏览次数:7  
标签:Network res self sock host Program ssh ip Log


Practice 1

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

class Device:
def init(self,ip,name):
self.ip = ip
self.name = name
self.vty = None
self.ssh_session = None

def ssh_connect(self):
    self.ssh_session = paramiko.SSHClient()
    self.ssh_session.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    self.ssh_session.connect(hostname=self.ip,port=22,username='huawei',password='Admin@123')
    self.vty = self.ssh_session.invoke_shell()

def ssh_close(self):
    self.ssh_session.close()

def ssh_send(self,cmd):
    self.vty.send((cmd+'\n').encode('utf-8'))
    time.sleep(0.5)
    res = self.vty.recv(6666)
    time.sleep(0.5)
    res = (res.decode('utf-8'))
    print(res)
    return res


def config_by_file(self,path):
    self.ssh_connect()
    with open(path,'r') as file:
        lines = file.readlines()
    self.ssh_send('sys imm')
    for line in lines:
        line = line.replace('\n','')
        self.ssh_send(line)
    self.ssh_send('q')
    self.ssh_close()

def set_ge(self,int,ip,mask):
    self.ssh_connect()
    self.ssh_send('sys imm')
    self.ssh_send(f'int {int}')
    self.ssh_send('undo sh')
    self.ssh_send('undo ports')
    self.ssh_send(f'ip address {ip} {mask}')
    self.ssh_send('q')
    self.ssh_send('q')
    self.ssh_close()

def put_file(self,local,remote):
    self.ssh_connect()
    tran = paramiko.Transport(self.ip,22)
    tran.connect(username='huawei',password='Admin@123')
    sftp = paramiko.SFTPClient.from_transport(tran)
    sftp.put(local,remote)
    time.sleep(1)
    self.ssh_close()

def set_defalut_route(self):
    self.ssh_connect()
    self.ssh_send('sys imm')
    self.ssh_send('ip route-static 0.0.0.0 0 NULL0')
    self.ssh_send('q')
    self.ssh_close()

def get_device_info(self):
    res = getCmd(
        SnmpEngine(),
        UsmUserData(
            userName='admin',
            authKey='Huawei@123',
            privKey='Huawei@123',
            authProtocol=usmHMACSHAAuthProtocol,
            privProtocol=usmAesCfb128Protocol,
        ),
        UdpTransportTarget((self.ip,161)),
        ContextData(),
        ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'))
    )
    return next(res)

def write_commands(self,local):
    self.ssh_connect()
    res = ''
    res += '\n###############################\n'
    res += self.ssh_send("display clock")
    res += '\n###############################\n'
    res += self.ssh_send('display device')
    res += '\n###############################\n'
    res += self.ssh_send('display health')
    res += '\n###############################\n'
    res += self.ssh_send('display power')
    res += '\n###############################\n'
    res += self.ssh_send('display fan')
    res += '\n###############################\n'
    self.ssh_close()
    with open(local,'a') as file:
        file.write(self.name+ ':\n')
        file.writelines(res)
        file.write('\n------------------------------\n')

def disable_ntp(self):
    try:
        with manager.connect(host=self.ip,
        port=830 ,
        username='huawei' ,
        password='Admin@123' ,
        allow_agent= False,
        hostkey_verify= False,
        look_for_keys= False,
        device_params={'name':'huawei'}) as m:
            res = ''
            with open('test/disable__ntp.txt','r') as file:
                lines = file.readlines()
                for line in lines:
                    res += line
            content = to_ele(res)
            res = m.rpc(content)
            if '<ok/>' in str(res):
                print('success')
            else:
                print('Failed!')

    except Exception as e :
        print('Error:',e)

if name == 'main':
host1 = Device('192.168.56.10','CE1')
host2 = Device('192.168.56.20','CE2')

host_list = []
host_list.append(host1)
host_list.append(host2)

host1.set_ge('vlanif 1','192.168.255.1','24')
host1.set_ge('vlanif 1','192.168.255.2','24')

host1.set_defalut_route()

host1.set_ge('ge 1/0/8','10.1.1.1','24')
host1.set_ge('ge 1/0/9','10.1.2.1','24')

for host in host_list:
    host.config_by_file('sftp.txt')

for host in host_list:
    host.put_file('snmp.txt','/snmp.txt')

for host in host_list:
    host.config_by_file('snmp.txt')

for host in host_list:
    res = host.get_device_info()[-1][-1]
    print(f'{host.name}:\n{res}')

for host in host_list:
    host.write_commands('log_2.txt')

for host in host_list:
    host.config_by_file('netconf.txt')

for host in host_list:
    host.disable_ntp()

client:

client_ip = '192.168.56.20'
client_port = 6666
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((client_ip,client_port))
msg = (b'z'.zfill(1024)).encode()
sock.send(msg)
res = sock.recv(1024)
print(res.decode())
sock.close()

server:

server_ip = '192.168.56.10'
server_port = 6666
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((server_ip,server_port))
sock.listen(5)

while True:
sock_client,sock_ip = sock.accept()
print(sock_ip,' has been connected!')
res = sock_client.recv(1024)
if res:
print(res)
msg = ('success').encode()
sock_client.send(msg)
sock_client.close()

socket:

UDP

import socket
server_ip = '127.0.0.1'
server_port = 6666
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((server_ip,server_port))

while True:
data,client_ip = sock.recvfrom(1024)
print(client_ip,'has connected')
print(data.decode())
msg = 'connected has been created'
sock.sendto(msg.encode(),client_ip)

UDP

import socket
server_ip = '127.0.0.1'
server_port = 6666
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
msg = b'a'.zfill(1024)
sock.sendto(msg,(server_ip,server_port))
res = sock.recv(1024)
print(res.decode())
sock.close()

标签:Network,res,self,sock,host,Program,ssh,ip,Log
From: https://www.cnblogs.com/heydom/p/18458095

相关文章

  • The Network Program Log Three(代码调试过程3)
    ​importpysharkimportos没有提示files=os.listdir('./shark_files/')forfileinfiles:print(file)ps=pyshark.FileCapture('./shark_files/'+file,tshark_path='D:/ProgramFiles/Wireshark/Wireshark.exe')forpktinps:prin......
  • The Network Program Log Two (Scapy)
    ​【Scapy】【使用scapy处理数据包】scapy的使用fromscapy.allimport*fromscapy.layers.inetimport*pac=dir(scapy.layers)print(pac) #执行代码后,会输出Scapy中的各层['builtins','cached','doc','file','loader','name&......
  • 【Kubernets】容器网络基础二:通讲CNI(Container Network Interface)容器网络接口实现方
    文章目录背景知识Underlay网络Overlay网络一、基本概念二、工作原理三、实现方案四、应用场景两者对比示意图CNI实现有哪些?FlannelFlannel的工作原理Flannel的主要组件数据传输机制总结Calico一、架构基础二、核心组件与功能三、路由与数据包转发四、安全策略五、数......
  • 关于我、重生到500年前凭借C语言改变世界科技vlog.2
    文章目录1.数据类型的介绍1.1数据类型分类1.2sizeof操作符1.3signed和unsigned2.变量的介绍2.1创建与初始化2.2分类2.3存储3.操作符的介绍3.1算术操作符:+、-、*、/、%3.2赋值操作符:=和复合赋值3.3单目操作符:++、--、+、-4.强制类型转换5.占位符的介绍及使用6......
  • 金慧-综合管理信息系统 LoginBegin.aspx SQL注入复现
    0x01产品描述:        金慧-综合管理信息系统(以下简称“金慧综合管理系统”)是上海金慧软件有限公司基于多年行业系统研发和实施经验,为各类企业量身定制的一套综合性管理解决方案。该系统旨在通过信息化手段,提升企业的管理效率,优化资源配置,实现办公自动化和无纸化办公......
  • 关于QEI(增量编码器)的verilog程序
    关于QEI的Verilog程序其实比较简单的,但是opencores上没有现成的程序,FPGA4FUN上有一个4倍频计数程序[1],但是没有一个详细原理分析过程,[2]描述了一个编码器的VHDL代码,但是觉得很复杂,为此我分析了一下增量编码器的旋转过程和AB相的电平变化规律,在这个基础上开发了QEI的Verilog程序,首......
  • MySQL之innodb_flush_log_at_trx_commit和sync_binlog
    innodb_flush_log_at_trx_commit和sync_binlog两个参数是控制MySQL磁盘写入策略以及数据安全性的关键参数,它们的配置对于mysql性能有很大的影响一、innodb_flush_log_at_trx_commitinnodb_flush_log_at_trx_commit:是InnoDB引擎特有的,ib_logfile的刷新方式(ib_logfile:存放In......
  • 全志用户层修改开机logo
    参考tina系统应用层更新开机logo_tinauboot加载bootlogo-CSDN博客 全志tina系统的开机logo显示方式有两种。分别是:是uboot中读取logo到内存中,然后kernel去显示/common/board_r.c init_sequence_r #ifdefCONFIGREADLOGOFORKERNEL sunxi_read_bootlogo, rb......
  • 机器学习之神经网络Neural Network
    第一部分:基本含义神经网络(NeuralNetwork)是一种模仿人脑神经元连接方式的机器学习模型,用于处理复杂的非线性问题。通过大量的参数和层级结构,神经网络可以学习数据中的特征,应用于分类、回归等任务。机器学习和人类实现人生巅峰的例子对比:如果把人比作神经网络,一次次摔倒就是......
  • 《Programming from the Ground Up》阅读笔记:p217-p238
    《ProgrammingfromtheGroundUp》学习第11天,p217-p238总结,总计22页。一、技术总结1.Ccompilingp216,Ccompilingissplitintotwostages-thepreprocessorandthemaincompiler。注:感觉这个写法不好,因为preprocessor和compiler都是对象,这里应该指动作。应该是:Cco......