I used following python script to create a custom topology in mininet using sudo Python My_topology.py :
from mininet.topo import Topo
from mininet.node import Node
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.node import RemoteController
import os
import sys
logging.getLogger().setLevel(logging.INFO)
class MyTopo (Topo):
def __init__(self, ipBase='10.0.0.0/8'):
Topo.__init__(self)
global host_list
# Add hosts and switches
s1 = self.addSwitch('s1')
for i in range(1, 21):
self.addHost('h%s'%i)
host_list.append('h%s'%i)
self.addLink('h%s'%i, s1)
def attack():
h1 = net.get('h1')
h1.cmd('sudo python .../My_SYNflood_attack.py')
topo = MyTopo()
net = Mininet(topo, controller=lambda name: RemoteController(name,
ip= '127.0.0.1', protocol= 'tcp', port= 6633), autoSetMacs= True)
net.start()
attack()
CLI(net)
net.stop()
As you see in attack function I used another .py script to send TCP packets from host h1 t another host. My_SYNflood_attack.py is as follow:
from scapy.all import *
import os
import sys
import random
import argparse
srcIP = '10.0.0.1'
dstIP = '10.0.0.10'
srcPort = 5555
dstPort = 4444
def randInt():
x = random.randint(1000,9000)
return x
def SYN_Flood(srcIP,dstIP,dstPort,counter):
total = 0
print("Packets are sending ...")
for x in range (0,counter):
s_port = randInt()
s_eq = randInt()
w_indow = randInt()
IP_Packet = IP ()
IP_Packet.src = srcIP
IP_Packet.dst = dstIP
TCP_Packet = TCP ()
TCP_Packet.sport = s_port
TCP_Packet.dport = dstPort
TCP_Packet.flags = "S"
TCP_Packet.seq = s_eq
TCP_Packet.window = w_indow
send(IP_Packet/TCP_Packet, verbose=0)
total+=1
sys.stdout.write("\nTotal packets sent: %i\n" % total)
def main():
SYN_Flood(srcIP, dstIP,dstPort,10)# 10 is number of packets
if __name__ == "__main__":
main()
So as you see in second script I set source and destination IP address statically, now I want to send source an destination IP address from first script and call My_SYNflood_attack.py in attack function like this: h1.cmd('sudo python .../My_SYNflood_attack.py 10.0.0.2 10.0.0.3')
How can I do it??
are you looking for something like this?
def attack():
h1 = net.get('h1')
h1.cmd('sudo python .../My_SYNflood_attack.py 10.0.0.2, 10.0.0.3')
and:
scrIP = sys.argv[1]
dstIP = sys.argv[2]
You can use to call another python script with arguments:
subprocess.call(['python', '.../My_SYNflood_attack.py.py', somescript_arg1, somescript_val1,...])
Related
import scapy.all as scapy
import optparse
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-r", "--range", dest="range", help="Use --range To Scan your Wifi Clients")
options = parser.parse_args()[0]
if not options.range:
parser.error("Please Specify an Option")
else:
return options
def scan(ip):
Ip_Addr = scapy.ARP(pdst=ip)
Mac_Addr = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
add_IpMac = Mac_Addr/Ip_Addr
(answered, unanswered) = scapy.srp(add_IpMac, timeout=1, verbose=False)
result_list =[]
for list in answered:
result_dic ={
"ip": list[1].psrc,
"mac": list[1].hwsrc
}
result_list.append(result_dic)
return(result_list)
def print_results(result_list):
print("\n")
print(" IP\t\t\t\tMac")
print("\n-----------------------------------------")
for result in result_list:
print(result["ip"]+"\t\t"+ result["mac"])
options = get_arguments()
result_dic = scan(options.range)
print_results(result_dic)
I made a simple IP Scanner which I use to scan the Local Network. I want to get the Hostname like netdiscover. Is there a way to get every Hostname in the local network with scapy.all? Here is my Python Script where I want insert the Hostname:
Im trying to send a 8 digit pin code from one computer to another, the code works when both of the computers are on the same networks.But there seems to be a problem when they are not on the same network. it just doesnt send the pin to the server pc.
receives the data from the client and saves it
server.py
import socket
import json
import Classes
def recive_pin(s_data):
pin = s_data.recv(int(s_data.recv(1).decode())).decode()
return pin
def main():
# gets port from json file
with open("Config.JSON", 'r') as f:
json_data = json.load(f)
port = json_data["load"]["port"]
# create the tcp socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# binds the socket to localhost , config port number
ip = '0.0.0.0'
s.bind((ip, port))
user_data = {}
while 1:
s.listen()
s_data, address = s.accept()
command = s_data.recv(1).decode()
if command == "P":
user_data[recive_pin(s_data)] = address
print(user_data)
if __name__ == '__main__':
main()
client.py
create a 8 digit code and sends it to the server
import socket
import json
import Classes
def main():
# gets the user input controlled/controller.
with open("Config.JSON", 'r') as f:
json_data = json.load(f)
port = json_data["load"]["port"]
ip = json_data["load"]["ip"]
c = Classes.handler(ip, port)
x = Classes.pin.create_pin()
c.send_pin(x)
if __name__ == '__main__':
main()
Classes.py
import random
import string
import socket
class handler:
def __init__(self, comunication_ip=0, port=0, ):
self.__comunication_ip = comunication_ip
self.__port = int(port)
# type of command to send to the server
# tuple of the server details
self.__server_details = (self.__comunication_ip, self.__port)
def send_pin(self, verification_pin):
# command type : Send_pin("P")
command_type = "P"
# creates a socket to send the pin to the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# adds the type of the command and the length of the pin to the Pin.
msg = command_type + str(len(verification_pin)) + verification_pin
s.connect(self.__server_details)
s.send(msg.encode())
class pin:
#staticmethod
# def __init__(self, defult_pin=0):
# self.__pin = defult_pin
def create_pin():
characters = string.ascii_letters + string.digits + string.punctuation
verification_pin = str(''.join(random.choice(characters) for length in range(8)))
return str(verification_pin)
i also use a Json file to save the port number and the server ip :
{
"load":{
"ip":"10.100.102.94",
"port": 12000
}
}
I want/need to make this code run inside OBS as a script. I took this OSC Sender for OBS that it does what the name says: it sends OSC messages. But, inside the code, the server part is commented, because it doesn't work... right out of the box. It is needed to run OBS with LD_PRELOAD=/path/libpython3.7.so.
I modified the code but (uncommented lines) but, when server is opened, OBS stays unusable, blocked. So, I tried the "Async Server" - "Concurrent Mode" of python-osc. I take the example from its wiki (that it works in a console) and I mixed with the other script. I made a nice code... but it makes something weird. This is the code:
"""
"""
# osc data
import argparse
import random
import time
import math
import asyncio
from pythonosc import osc_message_builder
from pythonosc import udp_client
from pythonosc.dispatcher import Dispatcher
from pythonosc.osc_server import AsyncIOOSCUDPServer
client = None
server = None
#obs !
import obspython as obs
pleaseLog = False
host = None
serverPort = None
# transport = None
async def loop():
"""Example main loop that only runs for 10 iterations before finishing"""
for i in range(10):
print(f"Loop {i}")
await asyncio.sleep(.5)
async def init_main():
# global transport
server = AsyncIOOSCUDPServer((host, serverPort), dispatcher, asyncio.get_event_loop())
transport, protocol = await server.create_serve_endpoint() # Create datagram endpoint and start serving
await loop() # Enter main loop of program
transport.close() # Clean up serve endpoint
def handleOSC(*args):
for i in args:
print(i)
# defines script description
def script_description():
return '''Send OSC data when source is activated if source name begins with /'''
# defines user properties
def script_properties():
global props
props = obs.obs_properties_create()
obs.obs_properties_add_text(props, "host", "Host IP", obs.OBS_TEXT_DEFAULT)
obs.obs_properties_add_int(props, "clientPort", "Host port", 1, 400000, 1)
obs.obs_properties_add_bool(props, "logOscOutput", "Log OSC output")
obs.obs_properties_add_int(props, "serverPort", "Listen port", 1, 400000, 1)
return props
def script_defaults(settings):
obs.obs_data_set_default_string(settings, "host", "127.0.0.1")
obs.obs_data_set_default_int(settings, "clientPort", 10000)
obs.obs_data_set_default_int(settings, "serverPort", 10001)
def source_activated(cd):
global pleaseLog
source = obs.calldata_source(cd, "source")
if source is not None:
name = obs.obs_source_get_name(source)
if name[0] == "/":
client.send_message(name, 1)
if (pleaseLog):
print("send " + name)
def script_load(settings):
global dispatcher
global host
sh = obs.obs_get_signal_handler()
obs.signal_handler_connect(sh, "source_activate", source_activated)
dispatcher = Dispatcher()
dispatcher.map("/*", handleOSC)
# def script_unload():
# global transport
# print(f'script_unload(settings)')
# transport.close() # Clean up serve endpoint
def script_update(settings):
global host
global client
global server
global clientPort
global serverPort
global pleaseLog
pleaseLog = obs.obs_data_get_bool(settings, "logOscOutput")
host = obs.obs_data_get_string(settings, "host")
clientPort = obs.obs_data_get_int(settings, "clientPort")
serverPort = obs.obs_data_get_int(settings, "serverPort")
# Client
client = udp_client.SimpleUDPClient(host, clientPort)
print("target set to "+host+":"+str(clientPort)+"")
# Server
print("serving in "+host+":"+str(serverPort)+"")
asyncio.run(init_main())
I'm not a programmer, so asyncio is a mess for me. I don't understand it. But I know what it does and what I'd like it to do.
When the script is loaded (in script_update(settings)), it opens the server and run loop() function. This function is a 5 seconds loop that prints some text. If I connect to the correct port from PureData and send some OSC messages, these messages arrives to OBS... but all of them drops together when the loop finishes. Meanwhile, there's nothing, OBS is blocked and nothing is in Script Log.
If I run the python-osc asyncio example code in a console, while loop is being executed, every Loop 0, Loop 1, etc, and every message arrives and all of them are printed at the right time.
How should I get this code to work? I need to open that server and run a much more code at the same time. I'm using OBS like a game engine.
Finally, I didn't use Asyncio. Instead of that, I use the Blocking Server method but inside a threading.Thread() function. For the moment, it is working right in this way.
It's important to close port when unload or reload script.
Oro, Treblig_Punisher (users from OBS Discor) helped me to achieve this.
"""
"""
# osc data
import argparse, random, time, math, threading
from pythonosc import osc_message_builder
from pythonosc import udp_client
from pythonosc import dispatcher
from pythonosc import osc_server
targetIp = "127.0.0.1"
targetPort = 10000
serverPort = 10008
client = None
server = None
#obs !
import obspython as obs
pleaseLog = False
def handleOSC(address, args, data):
print (address)
print (args)
print (data)
# defines script description
def script_description():
return '''Send and receive OSC messages'''
# defines user properties
def script_properties():
#global props
props = obs.obs_properties_create()
obs.obs_properties_add_text(props, "host", "Host IP", obs.OBS_TEXT_DEFAULT)
obs.obs_properties_add_int(props, "port", "Host port", 1, 400000, 1)
obs.obs_properties_add_bool(props, "logOscOutput", "Log OSC output")
obs.obs_properties_add_int(props, "serverPort", "Listen port", 1, 400000, 1)
return props
def script_defaults(settings):
obs.obs_data_set_default_string(settings, "host", targetIp)
obs.obs_data_set_default_int(settings, "port", targetPort)
obs.obs_data_set_default_int(settings, "serverPort", serverPort)
# Cuando se activa un source
def source_activated(cd):
global pleaseLog
source = obs.calldata_source(cd, "source")
if source is not None:
name = obs.obs_source_get_name(source)
current_scene = obs.obs_scene_from_source(obs.obs_frontend_get_current_scene())
scene_item = obs.obs_scene_find_source(current_scene, name)
boolean = obs.obs_sceneitem_visible(scene_item)
print(boolean)
if name[0] == "/":
client.send_message(name, boolean)
if (pleaseLog):
print("send " + name + boolean)
def script_load(settings):
global despachante
sh = obs.obs_get_signal_handler()
obs.signal_handler_connect(sh, "source_activate", source_activated)
despachante = dispatcher.Dispatcher()
despachante.map("/*", handleOSC)
def script_unload():
global server
server.server_close()
def script_update(settings):
global host
global port
global client
global server
global pleaseLog
pleaseLog = obs.obs_data_get_bool(settings, "logOscOutput")
host = obs.obs_data_get_string(settings, "host")
port = obs.obs_data_get_int(settings, "port")
# Client
client = udp_client.SimpleUDPClient(host, port)
print("target set to "+host+":"+str(port)+"")
# Server
serverPort = obs.obs_data_get_int(settings, "serverPort")
try:
server.server_close()
except:
print('*Server aun no creado')
# raise
server = osc_server.BlockingOSCUDPServer(("127.0.0.1", serverPort), despachante)
t = threading.Thread(target=server_th, args=([settings]))
t.daemon = True
t.start()
# Loop every 1000ms
# obs.timer_remove(funcion_loop)
# if and source_name != "":
# obs.timer_add(funcion_loop, 1000)
# Threading function
def server_th(settings):
print(f'Serving on {server.server_address}')
server.serve_forever() # Blocks forever
im beginner and i have tried for a lot
code :
conn = netmiko.ConnectHandler(ip='10.254.60.10', device_type='cisco_ios',
username='user', password='P#ssw0rd')
print (conn.send_command('show interface Ethernet0/0 | i line|Des|Int'))
output like this
Ethernet0/0 is up, line protocol is up
Description: CUSTOMER A
Internet address is 10.254.60.69/30
how to auto ping to IP PtP using conn.send_command() based on result of show interface command?
example ping to 10.254.60.70
You get text
text = '''Ethernet0/0 is up, line protocol is up Description: CUSTOMER A
Internet address is 10.254.60.70/30'''
and you can get IP/MASK using string functions
address = text.split(' ')[-1]
print(address) # 10.254.60.70/30
and then you can use standard module ipaddress
import ipaddress
net = ipaddress.ip_interface(address)
ip = str(net.network.broadcast_address)
print( ip ) # 10.254.60.71
or not standard module netaddr
import netaddr
net = netaddr.IPNetwork(address)
ip = str(net.broadcast)
print( ip ) # 10.254.60.71
EDIT: Minimal working code
text = '''Ethernet0/0 is up, line protocol is up Description: CUSTOMER A
Internet address is 10.254.60.69/30'''
address = text.split(' ')[-1]
print(address) # 10.254.60.69/30
print('\n--- ipaddress ---\n')
import ipaddress
net = ipaddress.ip_interface(address)
print('ip :', net.ip ) # 10.254.60.69
print('ip+1:', net.ip+1 ) # 10.254.60.70
print('ip-1:', net.ip-1 ) # 10.254.60.68
#bip = net.network.broadcast_address
bip = str(net.network.broadcast_address)
print('bip :', bip ) # 10.254.60.71
print('\n--- netaddr ---\n')
import netaddr
net = netaddr.IPNetwork(address)
print('ip :', net.ip ) # 10.254.60.69
print('ip+1:', net.ip+1 ) # 10.254.60.70
print('ip-1:', net.ip-1 ) # 10.254.60.68
bip = net.broadcast
#bip = str(net.broadcast)
print('bip :', bip ) # 10.254.60.71
Result:
10.254.60.69/30
--- ipaddress ---
ip : 10.254.60.69
ip+1: 10.254.60.70
ip-1: 10.254.60.68
bip : 10.254.60.71
--- netaddr ---
ip : 10.254.60.69
ip+1: 10.254.60.70
ip-1: 10.254.60.68
bip : 10.254.60.71
This could be your sample and so easy minimal code with Netmiko :
from netmiko import ConnectHandler
cisco_Router = {
"device_type": "cisco_ios",
"host": "your_router_ip",
"username": "your_username",
"password": "your_password"}
with ConnectHandler(**cisco_Router) as net_connect:
result = net_connect.send_command("ping 4.2.2.4")
net_connect.disconnect()
print(result)
I haven't write it for netmiko yet, but I often use this code for paramiko.
import threading
from ping3 import ping
from queue import Queue
from ipaddress import ip_network, ip_address
import paramiko
import time
from termcolor import colored
import sys
import os
import subprocess
file1 = open('PING_OK.txt', 'w')
file2 = open('PING_NOK.txt', 'w')
hosts=[]
f1 = open('hostfile.txt', 'r')
devices= f1.readlines()
#print(devices)
for i in devices:
i = i.split()
hosts.append(i[0])
hosts_live = []
q = Queue()
for host in hosts:
q.put(host)
enter = "\r\n"
def ping2(ip_address):
from pythonping import ping
output = ping(ip_address, verbose=True)
output_list =output.rtt_avg_ms
print(output_list)
if output_list == 2000:
print("erişim yok"+ip_address)
file2.write(ip_address+"\n")
else:
print ("erişim var"+ip_address)
file1.write(ip_address + "\n")
def worker():
while True:
host = q.get()
ping2(host)
time.sleep(2)
q.task_done()
for i in range(1):#aynı anda bağlantı 15 ten fazla girilmemeli #
t = threading.Thread(target=worker)
t.deamon = True
t.start()
q.join()
file1.close()
file2.close()
TOpology Loop
I have a problem with the ARP loop. I have attached my python API code and the Simple_Swicth.py code that I used. As you can see the picture, I cannot able to ping h1 to h2. can able to help?
Here is my topology code:
#!/usr/bin/python
from mininet.node import Controller, RemoteController, OVSController
from mininet.net import Mininet
from mininet.node import OVSKernelSwitch, UserSwitch
from mininet.cli import CLI
from mininet.link import TCLink, Intf
from mininet.log import setLogLevel, info
def Topo1():
net = Mininet(controller=RemoteController, switch=OVSKernelSwitch)
info('*** Adding controll\n')
c0 = net.addController(name='c0', controller=RemoteController, ip='127.0.0.1', protocol='tcp', port=6633)
info('*** Add host\n')
h1 = net.addHost('h1')
h2 = net.addHost('h2')
info('*** Add switches\n')
s1 = net.addSwitch('s1')
s2 = net.addSwitch('s2')
s3 = net.addSwitch('s3')
s4 = net.addSwitch('s4')
s5 = net.addSwitch('s5')
s1.linkTo( h1 )
s1.linkTo( s2 )
s2.linkTo( s3 )
s2.linkTo( s4 )
s3.linkTo( s4 )
s4.linkTo( s5 )
s5.linkTo( h2 )
net.build()
c0.start
info('***Starting switches\n')
net.get('s1').start([c0])
net.get('s2').start([c0])
net.get('s3').start([c0])
net.get('s4').start([c0])
net.get('s5').start([c0])
info('***Post configure switches and hosts\n')
net.start()
net.pingAll()
CLI(net)
net.stop()
if __name__ == '__main__':
setLogLevel('info')
Topo1()
here is the simple_switch code for ryu remote controller. Does anyone know which part of the simple_Switch code that I need add extra code to manage ARP loop. And since I do not really good at it don you mind to let me know what kind of code should I use?
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ether_types
class SimpleSwitch13(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
def __init__(self, *args, **kwargs):
super(SimpleSwitch13, self).__init__(*args, **kwargs)
self.mac_to_port = {}
#set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
datapath = ev.msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
# install table-miss flow entry
#
# We specify NO BUFFER to max_len of the output action due to
# OVS bug. At this moment, if we specify a lesser number, e.g.,
# 128, OVS will send Packet-In with invalid buffer_id and
# truncated packet data. In that case, we cannot output packets
# correctly. The bug has been fixed in OVS v2.1.0.
match = parser.OFPMatch()
actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
ofproto.OFPCML_NO_BUFFER)]
self.add_flow(datapath, 0, match, actions)
def add_flow(self, datapath, priority, match, actions, buffer_id=None):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
actions)]
if buffer_id:
mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
priority=priority, match=match,
instructions=inst)
else:
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
match=match, instructions=inst)
datapath.send_msg(mod)
#set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
# If you hit this you might want to increase
# the "miss_send_length" of your switch
if ev.msg.msg_len < ev.msg.total_len:
self.logger.debug("packet truncated: only %s of %s bytes",
ev.msg.msg_len, ev.msg.total_len)
msg = ev.msg
datapath = msg.datapath
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
in_port = msg.match['in_port']
pkt = packet.Packet(msg.data)
eth = pkt.get_protocols(ethernet.ethernet)[0]
if eth.ethertype == ether_types.ETH_TYPE_LLDP:
# ignore lldp packet
return
dst = eth.dst
src = eth.src
dpid = datapath.id
self.mac_to_port.setdefault(dpid, {})
self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
# learn a mac address to avoid FLOOD next time.
self.mac_to_port[dpid][src] = in_port
if dst in self.mac_to_port[dpid]:
out_port = self.mac_to_port[dpid][dst]
else:
out_port = ofproto.OFPP_FLOOD
actions = [parser.OFPActionOutput(out_port)]
# install a flow to avoid packet_in next time
if out_port != ofproto.OFPP_FLOOD:
match = parser.OFPMatch(in_port=in_port, eth_dst=dst)
# verify if we have a valid buffer_id, if yes avoid to send both
# flow_mod & packet_out
if msg.buffer_id != ofproto.OFP_NO_BUFFER:
self.add_flow(datapath, 1, match, actions, msg.buffer_id)
return
else:
self.add_flow(datapath, 1, match, actions)
data = None
if msg.buffer_id == ofproto.OFP_NO_BUFFER:
data = msg.data
out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
in_port=in_port, actions=actions, data=data)
datapath.send_msg(out)