scapy - how to display bit fields flags as on off? - scapy

scapy provides with FlagsField which show as
flag1+flag2+flag5
Can this be printed as ?
flag1=on
flag2=on
flag3=off
flag4=off
flag5=on
flagField take array-
but class can be a enum/dictionary which indexes a bit position.

worked it
class CFlagsField(FlagsField):
def i2repr(self, pkt, x):
flgs = []
for (k, v) in self.names.iteritems():
tf = 'True' if x & (1<<k) else 'False'
flgs.append('{:<20}={:^7}'.format(v, tf))
return "\n".join(flgs)

Related

How to get the client's ip on the server for remote desktop

I am using the following function to implement a program that changes its behavior depending on the IP of the connected PC.
There is a problem with this function that if something tries to login and fails, it may get the IP of the failed one.
And now that we've encountered that possibility, the program is broken.
What edits do I need to make to make this function behave as expected?
import psutil
def get_ip(port=3389):
ip = ""
for x in psutil.net_connections():
if x.status == "ESTABLISHED" and x.laddr.port == port:
ip = x.raddr.ip
break
I changed the function based on Bijay Regmi's comment. Thank you. wmi was difficult for me, so I used win32evtlog to read it out little by little. I am working on improving readability and finding bugs little by little.
def systime(xml):
return datetime.fromisoformat(xml.find(f'{ns}System/{ns}TimeCreated').get('SystemTime')[:-2] + "+00:00")
def last_event(handle,
event_id,
condition: Callable[['Event'], bool] = None) -> Optional['Event']:
now = datetime.now(tz=timezone.utc)
while True:
events = win32evtlog.EvtNext(handle, 20)
if not events:
break
for event in events:
xml_content = win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventXml)
obj = Event(ET.fromstring(xml_content))
if obj.EventID == event_id:
if obj.SystemTime + timedelta(minutes=5) < now:
return None
if condition and not condition(obj):
continue
return obj
class Event:
def __init__(self, xml: ET.Element):
self.EventID = xml and xml.find(f'{ns}System/{ns}EventID').text
self.SystemTime = xml and systime(xml)
self.xml = xml
if self.EventID == '24':
self.IpAddress = xml.find(f'{ns}UserData/{{Event_NS}}EventXML/{{Event_NS}}Address').text
elif self.EventID == '4624':
self.IpAddress = xml.find(f'{ns}EventData/{ns}Data[#Name="IpAddress"]').text
else:
self.IpAddress = None

Difficulty inputting training dataset with python code

Please, I need help with this. Tried almost everything I know and nothing is working.
So I am working on carrying out performance evaluation on dendritic cell algorithm used to detect anomalies by accepting input signals(PAMP, Danger signals, Safe Signals) the project is based on using parameter tuning to carry out this analysis. Changing the algorithm parameters and evaluate each result.
Got the algorithm's ruby code from the book "clever algorithms" and converted it to python.
My problem is that I am finding it difficult inputting my dataset on the python code, I am using the Nsl-kdd'cup dataset.
Also, help on using this with Matlab will be much appreciated.
Please, I need help.
The python code
from random import randrange,random,randint
def rand_in_bounds(min,max):
return randrange(min, max)
# def random_vector(search_space): unused function
# arr=np.zeroes(5)
# return arr
def construct_pattern(class_label,domain,p_safe,p_danger):
set_=domain[class_label]
selection=randrange(len(set_))
pattern={}
pattern["class_label"]=class_label
pattern["input_"]=set_[selection]
pattern["safe"]=(random()*p_safe*100)
pattern["danger"]=(random()*p_danger*100)
return pattern
def generate_pattern(domain,p_anomaly,p_normal,prob_create_anom=0.5):
pattern=None
if random() < prob_create_anom:
pattern=construct_pattern("Anomaly",domain,1-p_normal,p_anomaly)
print(">Generated Anomaly",pattern["input_"])
else:
pattern=construct_pattern("Normal",domain,p_normal,1-p_anomaly)
return pattern
def initialize_cell(thresh):
cell={}
cell["lifespan"]=1000
cell["k"]=0
cell["cms"]=0
cell["migration_threshold"]=thresh[0]+((thresh[1]-thresh[0])*random())
cell["antigen"]={}
# print(cell)
return cell
def store_antigen(cell,input_):
cell["antigen"].setdefault(input_,0)
cell["antigen"][input_]+=1
def expose_cell(cell,cms,k,pattern,threshold):
cell["cms"]+=cms
cell["k"]+=k
cell["lifespan"]-=cms
store_antigen(cell,pattern["input_"])
if cell["lifespan"]<=0 : cell= initialize_cell(threshold)
def can_cell_migrate(cell):
return (cell["cms"]>=cell["migration_threshold"]) and
(len((cell["antigen"]))!=0)
def expose_all_cells(cells,pattern,threshold):
migrate=[]
cms=(pattern["safe"]+pattern["danger"])
k=pattern["danger"]-(pattern["safe"]*2)
for cell in cells:
expose_cell(cell,cms,k,pattern,threshold)
if can_cell_migrate(cell):
cell["class_label"]=("Anomaly" if cell["k"]>0 else "Normal")
migrate.append(cell)
print("________________________")
return migrate
def train_system(domain,max_iter,num_cells,p_anomaly,p_normal,thresh):
immature_cells=[]
immature_cells=[initialize_cell(thresh) for x in range(num_cells)]
migrated=[]
c=0
for x in range(max_iter):
pattern=generate_pattern(domain,p_anomaly,p_normal)
migrants=expose_all_cells(immature_cells,pattern,thresh)
for cell in migrants:
immature_cells=[ x for x in immature_cells if x is not cell]
immature_cells.append(initialize_cell(thresh))
migrated.append(cell)
c+=1
print(f'> iter= {c} new={len(migrants)} migrated={len(migrated)}')
return migrated
def classify_pattern(migrated,pattern):
input_=pattern["input_"]
num_cells,num_antigen=0,0
for cell in migrated:
if ((cell["class_label"]=="Anomaly") and (input_ in cell["antigen"])):
num_cells+=1
num_antigen+=cell["antigen"][input_]
if num_antigen==0:
return "Normal"
mcav=num_cells/num_antigen
return "Anomaly" if mcav>0.5 else "Normal"
def test_system(migrated,domain,p_anomaly,p_normal,num_trial=100):
correct_norm=0
for _ in range(num_trial):
pattern=construct_pattern("Normal",domain,p_normal,1-p_anomaly)
class_label=classify_pattern(migrated,pattern)
correct_norm += 1 if class_label=="Normal" else 0
print(f"Finished testing Normal inputs {correct_norm}/{num_trial}")
correct_anom=0
for _ in range(num_trial):
pattern=construct_pattern("Anomaly",domain,1-p_normal,p_anomaly)
class_label=classify_pattern(migrated,pattern)
correct_anom += 1 if class_label=="Anomaly" else 0
print(f"Finished testing Anomaly inputs {correct_anom}/{num_trial}")
return [correct_norm,correct_anom]
def execute(domain,max_iter,num_cells,p_anom,p_norm,thresh):
migrated=train_system(domain,max_iter,num_cells,p_anom,p_norm,thresh)
test_system(migrated,domain,p_anom,p_norm)
return migrated
if __name__ =="__main__":
# problem configuration
domain = {}
domain["Normal"]=[x for x in range(1,51)]
domain["Anomaly"]=[x*10 for x in range(1,6)]
domain["Normal"]=[x for x in domain["Normal"] if x not in domain["Anomaly"]]
p_anomaly=0.70
p_normal=0.95
#algorithm configuration
iterations=100
num_cells=10
thresh=[5,15]
execute(domain,iterations,num_cells,p_anomaly,p_normal,thresh)

pyomo: Connector for blocks not working

I'm trying to connect two blocks with the "Connector" class implemented in pyomo, using the following simple examplary code.
from pyomo.environ import *
m = ConcreteModel()
# Block 01
m.block_01 = Block()
m.block_01.flow = Var(within=NonNegativeReals, bounds=(2, 10))
m.block_01.OUT = Connector(initialize= {'flow': m.block_01.flow})
# Block 02
m.block_02 = Block()
m.block_02.flow = Var(within=NonNegativeReals)
m.block_02.IN = Connector(initialize= {'flow': m.block_02.flow})
m.con = Constraint(expr=m.block_01.OUT == m.block_02.IN)
def _obj(_m):
return _m.block_01.flow + _m.block_02.flow
m.obj = Objective(rule=_obj)
After "optimization" all variables take their lower bound values (m.block_01.flow = 2 and m.block_02.flow = 0). So the Connector seems not to transfer any data for the variables.
If I'm using:
m.con = Constraint(expr=m.block_01.flow == m.block_02.flow)
instead, it works. However this is not the idea of Connectors, right?
Any ideas about the reason for the problem?
Did you apply the expand_connectors transformation before sending your model to a solver?
TransformationFactory('core.expand_connectors').apply_to(m)

(WinApi) ChangeDisplaySettingsEx does not work

I'm trying to write a python script to switch the primary monitor.
I have 3 Monitors (one is plugged into my i5's graphics chip, and 2 are plugged into a ATI HD7870)
I wrote the following script:
import win32api as w
import win32con as c
i = 0
workingDevices = []
def setPrimary(id):
global workingDevices
return w.ChangeDisplaySettingsEx(
workingDevices[id].DeviceName,
w.EnumDisplaySettings(
workingDevices[id].DeviceName,
c.ENUM_CURRENT_SETTINGS
),
c.CDS_SET_PRIMARY | c.CDS_UPDATEREGISTRY | c.CDS_RESET) \
== c.DISP_CHANGE_SUCCESSFUL
while True:
try:
Device = w.EnumDisplayDevices(None, i, 1)
if Device.StateFlags & c.DISPLAY_DEVICE_ATTACHED_TO_DESKTOP: #Attached to desktop
workingDevices.append(Device)
i += 1
except:
break
print("Num Devices: ", len(workingDevices))
for dev in workingDevices:
print("Name: ", dev.DeviceName)
Invoking it leads to:
In [192]: %run test.py
Num Devices: 3
Name: \\.\DISPLAY1
Name: \\.\DISPLAY2
Name: \\.\DISPLAY7
In [193]: setPrimary(0)
Out[193]: True
In [194]: setPrimary(1)
Out[194]: True
In [195]: setPrimary(2)
Out[195]: True
So far it looks great, but the problem is: nothing changes. My monitors flicker shortly because of the CDS_RESET but the primary screen does not change, although ChangeDisplaySettingsEx returns DISP_CHANGE_SUCCESSFUL
Does anyone have an Idea why?
(I use Python 3.5.1 and PyWin32 build 220)
PS I use 1 as the third arg for EnumDisplayDevices because the msdn states it should be set to one, although the PyWin help says it should be set to 0.
But the behaviour of the script does not change independent of this value beeing one or zero
Ok, I found the solution.
Apperantly the primary monitor must always be at position (0, 0).
So when I tried to set another monitor to primary its position was set to (0, 0) which caused it to intersect with the old primary one.
It seems the way to go is to update the positions of all Monitors, and write those changes to the registry, and then once this is done apply the changes by calling ChangeDisplaySettingsEx() with default parameters.
This is my new (now working) code:
import win32api as w
import win32con as c
def load_device_list():
"""loads all Monitor which are plugged into the pc
The list is needed to use setPrimary
"""
workingDevices = []
i = 0
while True:
try:
Device = w.EnumDisplayDevices(None, i, 0)
if Device.StateFlags & c.DISPLAY_DEVICE_ATTACHED_TO_DESKTOP: #Attached to desktop
workingDevices.append(Device)
i += 1
except:
return workingDevices
def setPrimary(id, workingDevices, MonitorPositions):
"""
param id: index in the workingDevices list.
Designates which display should be the new primary one
param workingDevices: List of Monitors returned by load_device_list()
param MonitorPositions: dictionary of form {id: (x_position, y_position)}
specifies the monitor positions
"""
FlagForPrimary = c.CDS_SET_PRIMARY | c.CDS_UPDATEREGISTRY | c.CDS_NORESET
FlagForSec = c.CDS_UPDATEREGISTRY | c.CDS_NORESET
offset_X = - MonitorPositions[id][0]
offset_Y = - MonitorPositions[id][1]
numDevs = len(workingDevices)
#get devmodes, correct positions, and update registry
for i in range(numDevs):
devmode = w.EnumDisplaySettings(workingDevices[i].DeviceName, c.ENUM_CURRENT_SETTINGS)
devmode.Position_x = MonitorPositions[i][0] + offset_X
devmode.Position_y = MonitorPositions[i][1] + offset_Y
if(w.ChangeDisplaySettingsEx(workingDevices[i].DeviceName, devmode,
FlagForSec if i != id else FlagForPrimary) \
!= c.DISP_CHANGE_SUCCESSFUL): return False
#apply Registry updates once all settings are complete
return w.ChangeDisplaySettingsEx() == c.DISP_CHANGE_SUCCESSFUL;
if(__name__ == "__main__"):
devices = load_device_list()
for dev in devices:
print("Name: ", dev.DeviceName)
MonitorPositions = {
0: (0, -1080),
1: (0, 0),
2: (1920, 0)
}
setPrimary(0, devices, MonitorPositions)

PyQt4 QTextCursor change selectable character

How can I change the selectable characters of a QTextCursor, like adding a dot?
For example entering "MyClass" in a QPlainTextEdit the stanza
tc = self.textCursor()
tc.select(QtGui.QTextCursor.WordUnderCursor)
return tc.selectedText()
will returns "MyClass", but entering "MyClass." will returns an empty Qstring!
The problem continues, entering "MyClass.myMeth" will just returns "myMeth", but I need "MyClass.myMeth" :/
Thanks
Ok, I find a solution by replacing the call to WordUnderCursor by :
def textUnderCursor(self):
tc = self.textCursor()
isStartOfWord = False
if tc.atStart() or (tc.positionInBlock() == 0):
isStartOfWord = True
while not isStartOfWord:
tc.movePosition(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
if tc.atStart() or (tc.positionInBlock() == 0):
isStartOfWord = True
elif QtCore.QChar(tc.selectedText()[0]).isSpace():
isStartOfWord = True
return tc.selectedText().trimmed()

Resources