I am trying to send a request with name, id.no and mac address. This process i need to do for 100 times. i mean 100 different names and id.no's and mac address. I tried doing this. I want output as name1, 1234567679 and aa:bb:cc:dd:11:22. can someone please help me. I have pasted my code and output below
for i in range (1,10):
name = 'name'+str(i)
print name
id = 121333445500000
id += 1
print id
mac = "aa:bb:cc:dd:"
ee = 0
for j in range(0,9):
ee1 = '0'+str(ee + j)+':'
ff = 0
for k in range(0,10):
ff1 = ff+k
if ff1 < 10:
mac1 = mac + ee1 + '0' + str(ff1)
print mac1
else:
mac1 = mac + ee1 + str(ff1)
print mac1
Output:
name1
121333445500001
aa:bb:cc:dd:00:00
aa:bb:cc:dd:00:01
aa:bb:cc:dd:00:02
aa:bb:cc:dd:00:03
aa:bb:cc:dd:00:04
aa:bb:cc:dd:00:05
aa:bb:cc:dd:00:06
aa:bb:cc:dd:00:07
aa:bb:cc:dd:00:08
aa:bb:cc:dd:00:09
aa:bb:cc:dd:01:00
aa:bb:cc:dd:01:01
aa:bb:cc:dd:01:02
aa:bb:cc:dd:01:03
aa:bb:cc:dd:01:04
aa:bb:cc:dd:01:05
aa:bb:cc:dd:01:06
aa:bb:cc:dd:01:07
aa:bb:cc:dd:01:08
aa:bb:cc:dd:01:09
aa:bb:cc:dd:02:00
aa:bb:cc:dd:02:01
aa:bb:cc:dd:02:02
aa:bb:cc:dd:02:03
aa:bb:cc:dd:02:04
aa:bb:cc:dd:02:05
aa:bb:cc:dd:02:06
aa:bb:cc:dd:02:07
aa:bb:cc:dd:02:08
aa:bb:cc:dd:02:09
aa:bb:cc:dd:03:00
aa:bb:cc:dd:03:01
aa:bb:cc:dd:03:02
aa:bb:cc:dd:03:03
aa:bb:cc:dd:03:04
aa:bb:cc:dd:03:05
aa:bb:cc:dd:03:06
aa:bb:cc:dd:03:07
aa:bb:cc:dd:03:08
aa:bb:cc:dd:03:09
aa:bb:cc:dd:04:00
aa:bb:cc:dd:04:01
aa:bb:cc:dd:04:02
aa:bb:cc:dd:04:03
aa:bb:cc:dd:04:04
aa:bb:cc:dd:04:05
aa:bb:cc:dd:04:06
aa:bb:cc:dd:04:07
aa:bb:cc:dd:04:08
aa:bb:cc:dd:04:09
aa:bb:cc:dd:05:00
aa:bb:cc:dd:05:01
aa:bb:cc:dd:05:02
aa:bb:cc:dd:05:03
aa:bb:cc:dd:05:04
aa:bb:cc:dd:05:05
aa:bb:cc:dd:05:06
aa:bb:cc:dd:05:07
aa:bb:cc:dd:05:08
aa:bb:cc:dd:05:09
aa:bb:cc:dd:06:00
aa:bb:cc:dd:06:01
aa:bb:cc:dd:06:02
aa:bb:cc:dd:06:03
aa:bb:cc:dd:06:04
aa:bb:cc:dd:06:05
aa:bb:cc:dd:06:06
aa:bb:cc:dd:06:07
aa:bb:cc:dd:06:08
aa:bb:cc:dd:06:09
aa:bb:cc:dd:07:00
aa:bb:cc:dd:07:01
aa:bb:cc:dd:07:02
aa:bb:cc:dd:07:03
aa:bb:cc:dd:07:04
aa:bb:cc:dd:07:05
aa:bb:cc:dd:07:06
aa:bb:cc:dd:07:07
aa:bb:cc:dd:07:08
aa:bb:cc:dd:07:09
aa:bb:cc:dd:08:00
aa:bb:cc:dd:08:01
aa:bb:cc:dd:08:02
aa:bb:cc:dd:08:03
aa:bb:cc:dd:08:04
aa:bb:cc:dd:08:05
aa:bb:cc:dd:08:06
aa:bb:cc:dd:08:07
aa:bb:cc:dd:08:08
aa:bb:cc:dd:08:09
name2
121333445500001
aa:bb:cc:dd:00:00
aa:bb:cc:dd:00:01
aa:bb:cc:dd:00:02
aa:bb:cc:dd:00:03
aa:bb:cc:dd:00:04
aa:bb:cc:dd:00:05
aa:bb:cc:dd:00:06
aa:bb:cc:dd:00:07
aa:bb:cc:dd:00:08
aa:bb:cc:dd:00:09
aa:bb:cc:dd:01:00
aa:bb:cc:dd:01:01
aa:bb:cc:dd:01:02
aa:bb:cc:dd:01:03
aa:bb:cc:dd:01:04
aa:bb:cc:dd:01:05
aa:bb:cc:dd:01:06
aa:bb:cc:dd:01:07
aa:bb:cc:dd:01:08
aa:bb:cc:dd:01:09
aa:bb:cc:dd:02:00
aa:bb:cc:dd:02:01
aa:bb:cc:dd:02:02
aa:bb:cc:dd:02:03
aa:bb:cc:dd:02:04
aa:bb:cc:dd:02:05
aa:bb:cc:dd:02:06
aa:bb:cc:dd:02:07
aa:bb:cc:dd:02:08
aa:bb:cc:dd:02:09
aa:bb:cc:dd:03:00
aa:bb:cc:dd:03:01
aa:bb:cc:dd:03:02
aa:bb:cc:dd:03:03
aa:bb:cc:dd:03:04
aa:bb:cc:dd:03:05
aa:bb:cc:dd:03:06
aa:bb:cc:dd:03:07
aa:bb:cc:dd:03:08
aa:bb:cc:dd:03:09
aa:bb:cc:dd:04:00
aa:bb:cc:dd:04:01
aa:bb:cc:dd:04:02
aa:bb:cc:dd:04:03
aa:bb:cc:dd:04:04
aa:bb:cc:dd:04:05
aa:bb:cc:dd:04:06
aa:bb:cc:dd:04:07
aa:bb:cc:dd:04:08
aa:bb:cc:dd:04:09
aa:bb:cc:dd:05:00
aa:bb:cc:dd:05:01
aa:bb:cc:dd:05:02
aa:bb:cc:dd:05:03
aa:bb:cc:dd:05:04
aa:bb:cc:dd:05:05
aa:bb:cc:dd:05:06
aa:bb:cc:dd:05:07
aa:bb:cc:dd:05:08
aa:bb:cc:dd:05:09
aa:bb:cc:dd:06:00
aa:bb:cc:dd:06:01
aa:bb:cc:dd:06:02
aa:bb:cc:dd:06:03
aa:bb:cc:dd:06:04
aa:bb:cc:dd:06:05
aa:bb:cc:dd:06:06
aa:bb:cc:dd:06:07
aa:bb:cc:dd:06:08
aa:bb:cc:dd:06:09
aa:bb:cc:dd:07:00
aa:bb:cc:dd:07:01
aa:bb:cc:dd:07:02
aa:bb:cc:dd:07:03
aa:bb:cc:dd:07:04
aa:bb:cc:dd:07:05
aa:bb:cc:dd:07:06
aa:bb:cc:dd:07:07
aa:bb:cc:dd:07:08
aa:bb:cc:dd:07:09
aa:bb:cc:dd:08:00
aa:bb:cc:dd:08:01
aa:bb:cc:dd:08:02
aa:bb:cc:dd:08:03
aa:bb:cc:dd:08:04
aa:bb:cc:dd:08:05
aa:bb:cc:dd:08:06
aa:bb:cc:dd:08:07
aa:bb:cc:dd:08:08
aa:bb:cc:dd:08:09
name3
121333445500001
Hope this Helps
mac="0xaabbccdd0000"
for i in range(101):
mac = "{:012X}".format(int(mac, 16) + 1)
print(':'.join(mac[i]+mac[i+1] for i in range(0, len(mac), 2)))
Try this code
import time, random
mac = "aa:bb:cc:dd:"
for i in range(1,100):
name = 'name'+ str(i)
# getting random number for id
id = int(time.time()) + random.randrange(0, 100, 1)
# quotient in part 1
mac_end1 = "0" + str(int(i/10))
# remainder in part 2
mac_end2 = "0" + str(int(i%10))
mac1 = mac + mac_end1 + ":" + mac_end2
print name, id, mac1
Based on #tcpip, here is a more generic way
Script filename: mac_generator.py
#%%
import argparse
import sys
# sys.argv = ['']
parser = argparse.ArgumentParser()
parser.add_argument('-t',
'--total',
type=int,
default=100,
help="The total number of mac address to be generated")
parser.add_argument('-f',
'--file',
action="store_true",
help="Generate in filename mac_address.txt")
args = parser.parse_args()
print("Total number of MAC address to be generated is: {}".format(args.total))
#%%
mac="0x000000000001"
def print_mac():
for i in range(args.total - 1):
global mac
mac = "{:012X}".format(int(mac, 16) + 1)
print(':'.join(mac[i]+mac[i+1] for i in range(0, len(mac), 2)))
original_stdout = sys.stdout # Save a reference to the original standard output
if(args.file):
with open('mac_address.txt', 'w') as f:
sys.stdout = f # Change the standard output to the file we created.
print_mac()
sys.stdout = original_stdout # Reset the standard output to its origin
else:
print_mac()
Usage
usage: mac_generator.py [-h] [-t TOTAL] [-f]
optional arguments:
-h, --help show this help message and exit
-t TOTAL, --total TOTAL
The total number of mac address to be generated
-f, --file Generate in filename mac_address.txt
So, if you want to generate 100 MAC address, run ./mac_generator -t 100
I used the netaddr library, it makes it quite neat:
base = netaddr.EUI(emac2)
for m in range(1, count2):
value = base.value
value += 1
base._set_value(value)
macs.append(str(base))
Related
I am attempting to yield all results from a search api.
There are 3 key cases:
Case 1: There are 0 results yielded
Case 2: There are 1-9 results yielded
Case 3: There are 10 results yielded
In both cases 1 and 2, we can conclude that there are no results deeper. i.e if we searched for "iiiiia" and it yields 0 then that means there are no results for "iiiiia" and no results deeper than "iiiiia". If "iiiiia" yields 1-9 results, then we can concluded "iiiiia" yields 109 results and no results deeper.
In case 3, if we search for "iiiiia" and it yields 10, we can conclude that "iiiiia" has 10 results, and there may or may not be results deeper as 10 means 10+ results possible. In this case we would have to move one layer down the chain and traverse through those results. i.e "iiiiia0"-"iiiiiaz" and if any of those yield 10 we would also have to go one layer deeper.
an example of how this may look:
a
a0
a00
a000
a0000
a0001
...
a000z
a001
a002
a003
a0030
...
a0034
a00340
...
a0034z
a0035...
Here is my attempted code:
import json
from time import sleep
import urllib3
import requests
import re
import random
import sys
import numpy
# Saving the reference of the standard output
original_stdout = sys.stdout
header = {}
link = '/search?query='
http = requests.session()
fileName = '/output.txt'
hasCompleted = 0
number = '11'
def search(target):
global targetList
global link
global header
global http
resp = http.request('GET',link+target,headers=header)
match = re.findall('"key":"(.+?)","',resp.text)
if len(match) == 10:
return False
if len(match) == 0:
return " "
elif len(match) < 10:
return resp.text
def treeSearch():
global fileName
global number
global hasCompleted
if hasCompleted == 1:
new = (int(int(number, 36) / 36) + 1)
new = numpy.base_repr(new, 36)
number = new
hasCompleted = 0
if hasCompleted == 0:
x = 0
new = int(int(number, 36)*36)
new = numpy.base_repr(new, 36)
number = new
while x < 37:
new = int(int(number, 36) + 1)
new = numpy.base_repr(new, 36)
number = new
result = search(number)
print(number)
if result:
with open(fileName, 'a+') as f:
sys.stdout = f
print(result)
sys.stdout = original_stdout
x = x + 1
else:
treeSearch()
temp = number
number = (int(int(number, 36) / 36) + 1) #maybe not + 1
print(number)
number = numpy.base_repr(number, 36)
print(number)
result = search(number)
if not result == " ":
new = int(int(number, 36)*36)
new = numpy.base_repr(new, 36)
number = new
hasCompleted = 1
treeSearch()
Here is my output:
111
1111
11111
111111
1111111
11111111
111111111
1111111111
11111111111
111111111111
1111111111111
11111111111111
111111111111111
1111111111111111
1111111111111112
1111111111111113
1111111111111114
1111111111111115
1111111111111116
1111111111111117
1111111111111118
1111111111111119
111111111111111A
111111111111111B
111111111111111C
111111111111111D
111111111111111E
111111111111111F
111111111111111G
111111111111111H
111111111111111I
111111111111111J
111111111111111K
111111111111111L
111111111111111M
111111111111111N
111111111111111O
111111111111111P
111111111111111Q
111111111111111R
111111111111111S
111111111111111T
111111111111111U
111111111111111V
111111111111111W
111111111111111X
111111111111111Y
111111111111111Z
1111111111111120
1111111111111121
6316397706306666889217
11111111110QR5T
11111111110QR5U
11111111110QR5V
11111111110QR5W
11111111110QR5X
11111111110QR5Y
11111111110QR5Z
11111111110QR60
11111111110QR61
11111111110QR62
11111111110QR63
11111111110QR64
11111111110QR65
11111111110QR66
11111111110QR67
11111111110QR68
11111111110QR69
11111111110QR6A
11111111110QR6B
11111111110QR6C
11111111110QR6D
11111111110QR6E
11111111110QR6F
11111111110QR6G
11111111110QR6H
11111111110QR6I
11111111110QR6J
11111111110QR6K
11111111110QR6L
11111111110QR6M
11111111110QR6N
11111111110QR6O
11111111110QR6P
11111111110QR6Q
11111111110QR6R
11111111110QR6S
11111111110QR6T
11111111110QR6U
175455491841851850753
11111111110L4X
11111111110L4Y
11111111110L4Z
11111111110L50
11111111110L51
11111111110L52
11111111110L53
11111111110L54
11111111110L55
11111111110L56
11111111110L57
11111111110L58
11111111110L59
11111111110L5A
11111111110L5B
11111111110L5C
11111111110L5D
11111111110L5E
11111111110L5F
11111111110L5G
11111111110L5H
11111111110L5I
11111111110L5J
11111111110L5K
11111111110L5L
11111111110L5M
11111111110L5N
11111111110L5O
11111111110L5P
11111111110L5Q
11111111110L5R
11111111110L5S
11111111110L5T
11111111110L5U
11111111110L5V
11111111110L5W
11111111110L5X
11111111110L5Y
4873763662273662977
11111111110XT
11111111110XU
11111111110XV
11111111110XW
11111111110XX
11111111110XY
11111111110XZ
11111111110Y0
11111111110Y1
11111111110Y2
11111111110Y3
11111111110Y4
11111111110Y5
11111111110Y6
11111111110Y7
11111111110Y8
11111111110Y9
11111111110YA
11111111110YB
11111111110YC
11111111110YD
11111111110YE
11111111110YF
11111111110YG
11111111110YH
11111111110YI
11111111110YJ
11111111110YK
11111111110YL
11111111110YM
11111111110YN
11111111110YO
11111111110YP
11111111110YQ
11111111110YR
11111111110YS
11111111110YT
11111111110YU
135382323952046193
11111111110X
11111111110Y
11111111110Z
111111111110
111111111111
111111111121
111111111122
111111111123
111111111124
111111111125
111111111126
111111111127
111111111128
111111111129
11111111112A
11111111112B
11111111112C
11111111112D
11111111112E
11111111112F
11111111112G
11111111112H
11111111112I
11111111112J
11111111112K
11111111112L
11111111112M
11111111112N
11111111112O
11111111112P
11111111112Q
11111111112R
11111111112S
11111111112T
11111111112U
11111111112V
11111111112W
11111111112X
11111111112Y
11111111112Z
111111111130
111111111131
3760620109779064
11111111114
111111111141
111111111142
111111111143
111111111144
111111111145
111111111146
111111111147
111111111148
111111111149
11111111114A
11111111114B
11111111114C
11111111114D
11111111114E
11111111114F
11111111114G
11111111114H
11111111114I
11111111114J
11111111114K
11111111114L
11111111114M
11111111114N
11111111114O
11111111114P
11111111114Q
11111111114R
11111111114S
11111111114T
11111111114U
11111111114V
11111111114W
11111111114X
11111111114Y
3760620109779066
11111111116
11111111117
11111111118
11111111119
1111111111A
1111111111B
1111111111C
1111111111D
1111111111E
1111111111F
1111111111G
1111111111H
1111111111I
1111111111J
1111111111K
1111111111L
1111111111M
1111111111N
1111111111O
1111111111P
1111111111Q
1111111111R
1111111111S
1111111111T
1111111111U
1111111111V
1111111111W
1111111111X
1111111111Y
1111111111Z
11111111120
11111111121
11111111122
11111111123
11111111124
11111111125
11111111126
11111111127
104461669716087
1111111113
1111111114
1111111115
1111111116
1111111117
1111111118
1111111119
111111111A
111111111B
111111111C
111111111D
111111111E
111111111F
111111111G
111111111H
111111111I
111111111J
111111111K
111111111L
111111111M
111111111N
111111111O
111111111P
111111111Q
111111111R
111111111S
111111111T
111111111U
111111111V
111111111W
111111111X
111111111Y
111111111Z
1111111120
1111111121
1111111122
1111111123
1111111124
2901713047671
111111113
111111114
111111115
111111116
111111117
111111118
111111119
11111111A
11111111B
11111111C
11111111D
11111111E
11111111F
11111111G
11111111H
11111111I
11111111J
11111111K
11111111L
11111111M
11111111N
11111111O
11111111P
11111111Q
11111111R
11111111S
11111111T
11111111U
11111111V
11111111W
11111111X
11111111Y
11111111Z
111111120
111111121
111111122
111111123
111111124
80603140215
11111113
11111114
11111115
11111116
11111117
11111118
11111119
1111111A
1111111B
1111111C
1111111D
1111111E
1111111F
1111111G
1111111H
1111111I
1111111J
1111111K
1111111L
1111111M
1111111N
1111111O
1111111P
1111111Q
1111111R
1111111S
1111111T
1111111U
1111111V
1111111W
1111111X
1111111Y
1111111Z
11111120
11111121
11111122
11111123
11111124
2238976119
1111113
11111131
11111132
11111133
11111134
11111135
11111136
11111137
11111138
11111139
1111113A
1111113B
1111113C
1111113D
1111113E
1111113F
1111113G
1111113H
1111113I
1111113J
1111113K
1111113L
1111113M
1111113N
1111113O
1111113P
1111113Q
1111113R
1111113S
1111113T
1111113U
1111113V
1111113W
1111113X
1111113Y
1111113Z
11111140
11111141
2238976121
1111115
11111151
11111152
11111153
11111154
11111155
11111156
11111157
11111158
11111159
1111115A
1111115B
1111115C
1111115D
1111115E
1111115F
1111115G
1111115H
1111115I
1111115J
1111115K
1111115L
1111115M
1111115N
1111115O
1111115P
1111115Q
1111115R
1111115S
1111115T
1111115U
1111115V
1111115W
1111115X
1111115Y
1111115Z
11111160
11111161
2238976123
1111117
11111171
11111172
11111173
11111174
11111175
11111176
11111177
11111178
11111179
1111117A
1111117B
1111117C
1111117D
1111117E
1111117F
1111117G
1111117H
1111117I
1111117J
1111117K
1111117L
1111117M
1111117N
1111117O
1111117P
1111117Q
1111117R
1111117S
1111117T
1111117U
1111117V
1111117W
1111117X
1111117Y
1111117Z
11111180
11111181
2238976125
1111119
111111A
111111B
111111C
111111D
111111E
111111F
111111G
111111H
111111I
111111J
111111K
111111L
111111M
111111N
111111O
111111P
111111Q
111111R
111111S
111111T
111111U
111111V
111111W
111111X
111111Y
111111Z
1111120
1111121
1111122
1111123
1111124
1111125
1111126
1111127
1111128
1111129
111112A
62193783
111113
1111131
1111132
1111133
1111134
1111135
1111136
1111137
1111138
1111139
111113A
111113B
111113C
111113D
111113E
111113F
111113G
111113H
111113I
111113J
111113K
111113L
111113M
111113N
111113O
111113P
111113Q
111113R
111113S
111113T
111113U
111113V
111113W
111113X
111113Y
111113Z
1111140
1111141
62193785
111115
My code traverses in only deeper once then comes out, I will keep working on my code however I am hoping to find an easier solution or possibly a library that can perform this style of search. Thanks!
Essentially, I am trying to make a snakemake rule for trimming for both paired-end and single-end reads. My problem is that for unpaired reads, there is 1 output, but for paired reads, there are 2 outputs (technically 4 but for my rule, I've specified 2). The error I get I think has to do with my output.... I'll just show what I have first.
config.yaml:
sample_file: "sample.tab"
FASTQ_DIR: "/dir/data/fastq_files"
TRIMMED_DIR: "/dir/data/trimmed"
sample.tab:
Sample Layout
SRR11213896 SE
ERR3887380 PE
Snakefile:
configfile: "config.yaml"
FASTQ_DIR = config["FASTQ_DIR"]
TRIMMED_DIR = config["TRIMMED_DIR"]
import pandas as pd
sample_file = config["sample_file"]
samples_df = pd.read_table(sample_file).set_index("Sample", drop = True)
srr_samples = list(samples_df.index)
srr_unpaired = list(samples_df[samples_df["Layout"] == "SE"].index)
srr_paired = list(samples_df[samples_df["Layout"] == "PE"].index)
def get_reads(wc):
tag = samples_df.loc[samples_df.index == wc.sample, 'Layout'].iloc[0]
if tag == "SE":
return FASTQ_DIR + "/" + wc.sample + "_1M.fastq"
if tag == "PE":
return FASTQ_DIR + "/" + wc.sample + "_1M_R1.fastq", FASTQ_DIR + "/" + wc.sample + "_1M_R2.fastq"
rule all:
input:
expand(TRIMMED_DIR + "/{sample}_trimmed.fastq", sample = srr_unpaired),
expand(TRIMMED_DIR + "/{sample}_R1_trimmed.fastq", sample = srr_paired),
expand(TRIMMED_DIR + "/{sample}_R2_trimmed.fastq", sample = srr_paired)
rule trimmed:
input:
reads = get_reads
output:
unpaired = TRIMMED_DIR + "/{sample}_trimmed.fastq",
paired_r1 = TRIMMED_DIR + "/{sample}_R1_trimmed.fastq",
paired_r2 = TRIMMED_DIR + "/{sample}_R2_trimmed.fastq"
params:
tag = lambda wc: samples_df.loc[samples_df.index == wc.sample, 'Layout'].iloc[0],
to_trim = "TRAILING:30 SLIDINGWINDOW:4:15 MINLEN:15",
read = lambda wc: samples_df.loc[samples_df.index == wc.sample].index[0],
dir = TRIMMED_DIR + "/",
read_dir = FASTQ_DIR + "/"
run:
if params.tag == "SE":
shell("trimmomatic {params.tag} {input.reads} {output.unpaired} {params.to_trim}")
if params.tag == "PE":
shell("trimmomatic {params.tag} {input.reads} {output.paired_r1} {params.dir}{params.read}_R1_unpaired.fastq {output.paired_r2} {params.dir}{params.read}_R2_unpaired.fastq {params.to_trim}")
Running snakemake -n by itself gives no errors, but running snakemake I get this error, here is the snakemake log:
Building DAG of jobs...
Provided cores: 1
Rules claiming more threads will be scaled down.
Job counts:
count jobs
1 all
2 trimmed
3
rule trimmed:
input: /dir/data/fastq_files/ERR3887380_1M_R1.fastq, /dir/data/fastq_files/ERR3887380_1M_R2.fastq
output: /dir/data/trimmed/ERR3887380_trimmed.fastq, /dir/data/trimmed/ERR3887380_R1_trimmed.fastq, /dir/data/trimmed/ERR3887380_R2_trimmed.fastq
jobid: 2
wildcards: sample=ERR3887380
Will exit after finishing currently running jobs.
Exiting because a job execution failed. Look above for error message
Complete log: .snakemake/snakemake.log
I SUSPECT it's because in the output: section of my snakemake.log, there appears to be 3 outputs when for this read, there should only be 2. Does anyone have any ideas around this? Much help would be appreciated !!!!!
this is the original repo i'm trying to run in my computer: https://github.com/kreamkorokke/cs244-final-project
import os
import matplotlib.pyplot as plt
import argparse
from attacker import check_attack_type
IMG_DIR = "./plots"
def read_lines(f, d):
lines = f.readlines()[:-1]
for line in lines:
typ, time, num = line.split(',')
if typ == 'seq':
d['seq']['time'].append(float(time))
d['seq']['num'].append(float(num))
elif typ == 'ack':
d['ack']['time'].append(float(time))
d['ack']['num'].append(float(num))
else:
raise "Unknown type read while parsing log file: %s" % typ
def main():
parser = argparse.ArgumentParser(description="Plot script for plotting sequence numbers.")
parser.add_argument('--save', dest='save_imgs', action='store_true',
help="Set this to true to save images under specified output directory.")
parser.add_argument('--attack', dest='attack',
nargs='?', const="", type=check_attack_type,
help="Attack name (used in plot names).")
parser.add_argument('--output', dest='output_dir', default=IMG_DIR,
help="Directory to store plots.")
args = parser.parse_args()
save_imgs = args.save_imgs
output_dir = args.output_dir
attack_name = args.attack
if save_imgs and attack_name not in ['div', 'dup', 'opt'] :
print("Attack name needed for saving plot figures.")
return
normal_log = {'seq':{'time':[], 'num':[]}, 'ack':{'time':[], 'num':[]}}
attack_log = {'seq':{'time':[], 'num':[]}, 'ack':{'time':[], 'num':[]}}
normal_f = open('log.txt', 'r')
attack_f = open('%s_attack_log.txt' % attack_name, 'r')
read_lines(normal_f, normal_log)
read_lines(attack_f, attack_log)
if attack_name == 'div':
attack_desc = 'ACK Division'
elif attack_name == 'dup':
attack_desc = 'DupACK Spoofing'
elif attack_name == 'opt':
attack_desc = 'Optimistic ACKing'
else:
raise 'Unknown attack type: %s' % attack_name
norm_seq_time, norm_seq_num = normal_log['seq']['time'], normal_log['seq']['num']
norm_ack_time, norm_ack_num = normal_log['ack']['time'], normal_log['ack']['num']
atck_seq_time, atck_seq_num = attack_log['seq']['time'], attack_log['seq']['num']
atck_ack_time, atck_ack_num = attack_log['ack']['time'], attack_log['ack']['num']
plt.plot(norm_seq_time, norm_seq_num, 'b^', label='Regular TCP Data Segments')
plt.plot(norm_ack_time, norm_ack_num, 'bx', label='Regular TCP ACKs')
plt.plot(atck_seq_time, atck_seq_num, 'rs', label='%s Attack Data Segments' % attack_desc)
plt.plot(atck_ack_time, atck_ack_num, 'r+', label='%s Attack ACKs' % attack_desc)
plt.legend(loc='upper left')
x = max(max(norm_seq_time, norm_ack_time),max(atck_seq_time, atck_ack_time))
y = max(max(norm_seq_num, norm_ack_num),max(atck_seq_num, atck_ack_num))
plt.xlim(0, x)
plt.ylim(0,y)
plt.xlabel('Time (s)')
plt.ylabel('Sequence Number (Bytes)')
if save_imgs:
# Save images to figure/
if not os.path.exists(output_dir):
os.makedirs(output_dir)
plt.savefig(output_dir + "/" + attack_name)
else:
plt.show()
normal_f.close()
attack_f.close()
if __name__ == "__main__":
main()
after running this i get this error
Traceback (most recent call last):
File "plot.py", line 85, in <module>
main()
File "plot.py", line 66, in main
plt.xlim(0, a)
File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 1427, in xlim
ret = ax.set_xlim(*args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/axes/_base.py", line 3267, in set_xlim
reverse = left > right
TypeError: '>' not supported between instances of 'int' and 'list'
Done! Please check ./plots for all generated plots.
how can i solve this problem? or better yet if there is another way of running this project? i installed matplotlib via pip3 install matplotlib command (same with scapy) and my main python version is python2 right now but i run the project with python3, could the issue be about this? what am i missing? or is it about mininet itself?
The problem is in this line
x = max(max(norm_seq_time, norm_ack_time),max(atck_seq_time, atck_ack_time))
IIUC, you wanna assign to x the maximum value among all those four lists. However, when you pass two lists to the max function, such as max(norm_seq_time, norm_ack_time), it will return the list it considers the greater one, and not the highest value considering both lists.
Instead, you can do something like:
x = max(norm_seq_time + norm_ack_time + atck_seq_time + atck_ack_time)
This will concatenate the four lists into a single one. Then, the function will return the highest value among all of them. You might wanna do that to the calculation of y as well.
If this is not what you wanted, or if you have any further issues, please let us know.
with the help of a friend we solved this problem by changing a part in code into this:
max_norm_seq_time = max(norm_seq_time) if len(norm_seq_time) > 0 else 0
max_norm_ack_time = max(norm_ack_time) if len(norm_ack_time) > 0 else 0
max_atck_seq_time = max(atck_seq_time) if len(atck_seq_time) > 0 else 0
max_atck_ack_time = max(atck_ack_time) if len(atck_ack_time) > 0 else 0
x = max((max_norm_seq_time, max_norm_ack_time,\
max_atck_seq_time, max_atck_ack_time))
plt.xlim([0,x])
max_norm_seq_num = max(norm_seq_num) if len(norm_seq_num) > 0 else 0
max_norm_ack_num = max(norm_ack_num) if len(norm_ack_num) > 0 else 0
max_atck_seq_num = max(atck_seq_num) if len(atck_seq_num) > 0 else 0
max_atck_ack_num = max(atck_ack_num) if len(atck_ack_num) > 0 else 0
plt.ylim([0, max((max_norm_seq_num, max_norm_ack_num,\
max_atck_seq_num, max_atck_ack_num))])
```
writing here just in case anyone else needs it.
I wrote what I thought was a straightforward Python script to traverse a given directory and tabulate all the file suffixes it finds. The output looks like this:
OTUS-ASIO:face fish$ sufs
>>> /Users/fish/Dropbox/ost2/face (total 194)
=== 1 1 -
=== css 16 -----
=== gif 14 -----
=== html 12 ----
=== icc 87 --------------------------
=== jpg 3 -
=== js 46 --------------
=== png 3 -
=== zip 2 -
... which would be great, if those values were correct. They are not. Here's what happens when I run it in a subdirectory of the directory I listed above:
OTUS-ASIO:face fish$ cd images/
OTUS-ASIO:images fish$ sufs
>>> /Users/fish/Dropbox/ost2/face/images (total 1016)
=== JPG 3 -
=== gif 17 -
=== ico 1 -
=== jpeg 1 -
=== jpg 901 --------------------------
=== png 87 ---
... It only seems to go one directory level down. Running the script one level up didn't pick up on the 'jpeg' suffix at all, and seemed to miss a good 898 jpg files.
The script in question is here:
#!/usr/bin/env python
# encoding: utf-8
"""
getfilesuffixes.py
Created by FI$H 2000 on 2010-10-15.
Copyright (c) 2010 OST, LLC. All rights reserved.
"""
import sys, os, getopt
help_message = '''
Prints a list of all the file suffixes found in each DIR, with counts.
Defaults to the current directory wth no args.
$ %s DIR [DIR DIR etc ...]
''' % os.path.basename(__file__)
dirs = dict()
skips = ('DS_Store','hgignore')
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def getmesomesuffixes(rootdir, thisdir=None):
if not thisdir:
thisdir = rootdir
for thing in [os.path.abspath(h) for h in os.listdir(thisdir)]:
if os.path.isdir(thing):
getmesomesuffixes(rootdir), thing)
else:
if thing.rfind('.') > -1:
suf = thing.rsplit('.').pop()
dirs[rootdir][suf] = dirs[rootdir].get(suf, 0) + 1
return
def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "h", ["help",])
except getopt.error, msg:
raise Usage(msg)
for option, value in opts:
if option == "-v":
verbose = True
if option in ("-h", "--help"):
raise Usage(help_message)
if len(args) == 0:
args.append(os.getcwd())
for durr in [os.path.abspath(arg) for arg in args]:
if os.path.isdir(durr):
dirs[durr] = dict()
for k, v in dirs.items():
getmesomesuffixes(k)
print ""
for k, v in dirs.items():
sufs = v.items()
sufs.sort()
maxcount = reduce(lambda fs, ns: fs > ns and fs or ns, map(lambda t: t[1], sufs), 1)
mincount = reduce(lambda fs, ns: fs < ns and fs or ns, map(lambda t: t[1], sufs), 1)
total = reduce(lambda fs, ns: fs + ns, map(lambda t: t[1], sufs), 0)
print ">>>\t\t\t%s (total %s)" % (k, total)
for suf, sufcount in sufs:
try:
skips.index(suf)
except ValueError:
print "===\t\t\t%12s\t %3s\t %s" % (suf, sufcount, "-" * (int(float(float(sufcount) / float(maxcount)) * 25) + 1))
print ""
except Usage, err:
print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
print >> sys.stderr, "\t for help use --help"
return 2
if __name__ == "__main__":
sys.exit(main())
It seems that getmesomesuffixes() is subtly not doing what I want it to. I hate to ask such an annoying question, but if anyone can spot whatever amateur-hour error I am making with a quick once-over, it would save me some serious frustration.
Yeah, Won't you be better off if you used os.walk
for root, dirs, files in os.walk(basedir):
... do you stuff ..
See the example at
http://docs.python.org/library/os.html
Also look at os.path.splitext(path), a finer way to find the type of your file.
>>> os.path.splitext('/d/c/as.jpeg')
('/d/c/as', '.jpeg')
>>>
Both of these together should simplify your code.
import os
import os.path
from collections import defaultdict
def foo(dir='.'):
d = defaultdict(int)
for _, _, files in os.walk(dir):
for f in files:
d[os.path.splitext(f)[1]] += 1
return d
if __name__ == '__main__':
d = foo()
for k, v in sorted(d.items()):
print k, v
I'd like to make a very simple text (.txt) file. This python program needs to make a list of multiple ranges of IPs in a subnet, each taking up one line.
Example:
10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.51
10.10.27.52
10.10.27.53
10.10.27.54
The subnet mask will essentially always be a /24, so providing mask input is not necessary. The program can even default to only supporting a standard class C.
Also, I'd like to support common ranges for devices that we use. A prompt for say, "Printers?" will include .26 - .30. "Servers?" will include .5 - .7. "DHCP?" prompt always will include .51 - .100 of the subnet. "Abnormal?" will include .100 - .254.
Subnet? 10.10.27.1
Servers? Y
Printers? Y
DHCP? Y
Abnormal? N
Output being:
10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.7
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.30
10.10.27.51 (all the way to .100)
What is the best way to code this?
It looks like a few for loops are all you need:
network = '10.10.27'
for host in xrange(100, 255):
print("{network}.{host}".format(**locals()))
I would keep the script simple, just output all addresses as needed :)
def yesno(question):
output = input(question).lower()
if output == 'y':
return True
elif output == 'n':
return False
else:
print '%r is not a valid response, only "y" and "n" are allowed.' % output
return yesno(question)
addresses = []
subnet = input('Subnet? ')
# Remove the last digit and replace it with a %d for formatting later
subnet, address = subnet.rsplit('.', 1)
subnet += '%d'
addresses.append(int(address))
if yesno('Servers? '):
addresses += range(5, 8)
if yesno('Printers? '):
addresses += range(26, 31)
if yesno('DHCP? '):
addresses += range(51, 101)
if yesno('Abnormal? '):
addresses += range(100, 255)
for address in addresses:
print subnet % address
Here is a quick little script I threw together...
import socket
import sys
ranges = {'servers':(5, 8), 'printers':(26, 31), 'dhcp':(51, 101), 'abnormal':(101, 256)}
subnet = raw_input("Subnet? ")
try:
socket.inet_aton(subnet)
except socket.error:
print "Not a valid subnet"
sys.exit(1)
ip_parts = subnet.split(".")
if len(ip_parts) < 3:
print "Need at least three octets"
sys.exit(1)
ip_parts = ip_parts[:3]
ip = ".".join(ip_parts)
include_groups = []
last_octets = []
servers = raw_input("Servers? ")
printers = raw_input("Printers? ")
dhcp = raw_input("DHCP? ")
abnormal = raw_input("Abnormal? ")
if servers == "Y":
include_groups.append('servers')
if printers == "Y":
include_groups.append('printers')
if dhcp == "Y":
include_groups.append('dhcp')
if abnormal == "Y":
include_groups.append('abnormal')
for group in include_groups:
last_octets.extend([x for x in xrange(ranges[group][0], ranges[group][1])])
print "%s.1" %(ip)
for octet in last_octets:
print "%s.%s" %(ip, octet)