python执行效率有多低_python – Scapy的低性能

我正在创建一个脚本,将来自Tap0的所有流量发送到Eth0,并将来自Eth0的所有流量发送到Tap0.在网上找到很多例子后,我设法让它发挥作用.我遇到的问题是性能非常低.

在不使用脚本的情况下在2个VM之间进行ping操作,所需时间不到1毫秒.使用脚本需要大约15ms.

当我使用scp从VM向另一个VM发送10 MB文件时,平均值.没有脚本,传输速率是12 Mbps.使用该脚本,它降至不到1 Mbps.

我知道Python实际上并不是处理网络流量最快的语言,但它是否会变慢?

有没有办法优化这段代码?

我的VM是Ubuntu 10.04 32位.

这是代码:

import os,sys,getopt,struct,re,string,logging

from socket import *

from fcntl import ioctl

from select import select

from scapy.all import *

TUNSETIFF = 0x400454ca

IFF_TAP = 0x0002

TUNMODE = IFF_TAP

ETH_IFACE = "eth0"

TAP_IFACE = "tap0"

conf.iface = ETH_IFACE

# Here we capture frames on ETH0

s = conf.L2listen(iface = ETH_IFACE)

# Open /dev/net/tun in TAP (ether) mode (create TAP0)

f = os.open("/dev/net/tun", os.O_RDWR)

ifs = ioctl(f, TUNSETIFF, struct.pack("16sH", "tap%d", TUNMODE))

# Speed optimization so Scapy does not have to parse payloads

Ether.payload_guess=[]

os.system("ifconfig eth0 0.0.0.0")

os.system("ifconfig tap0 192.168.40.107")

os.system("ifconfig tap0 down")

os.system("ifconfig tap0 hw ether 00:0c:29:7a:52:c4")

os.system("ifconfig tap0 up")

eth_hwaddr = get_if_hwaddr('eth0')

while 1:

r = select([f,s],[],[])[0] #Monitor f(TAP0) and s(ETH0) at the same time to see if a frame came in.

#Frames from TAP0

if f in r: #If TAP0 received a frame

# tuntap frame max. size is 1522 (ethernet, see RFC3580) + 4

tap_frame = os.read(f,1526)

tap_rcvd_frame = Ether(tap_frame[4:])

sendp(tap_rcvd_frame,verbose=0) #Send frame to ETH0

#Frames from ETH0

if s in r: #If ETH0 received a frame

eth_frame = s.recv(1522)

if eth_frame.src != eth_hwaddr:

# Add Tun/Tap header to frame, convert to string and send. "\x00\x00\x00\x00" is a requirement when writing to tap interfaces. It is an identifier for the Kernel.

eth_sent_frame = "\x00\x00\x00\x00" + str(eth_frame)

os.write(f, eth_sent_frame) #Send frame to TAP0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值