Im currently writing a script for python that will enable users to easily configure snort, I have a rule to protect TCP port 23 from access called IoTProtect with the following syntax:
reject tcp any any -> 169.254.183.24 23 (msg:Unauthorized access to IoT device!; sid:00000000;rev:003; )
The issue is that I have added functionality so that a user can add an IP address and this rule will be applied for that IP as well, however, for the rule to work the SID must be incremented by one or be unique.
Currently the python script i've created is:
import fileinput
def incrementsid():
incremented = 0
added = incremented + 2
text = "sid:00000000"
new_text = "sid:0000000{}".format(added)
for line in fileinput.input("C:\\Users\\Admin\\Desktop\\Test\\IoTProtection.rules", inplace = 1):
if text in line:
print(line.replace(line,new_text))
print("Sid replaced!")
else:
print(line.strip())
incrementsid()
However what actually happens is I receive this output:
reject tcp any any -> 169.254.183.24 23 (msg:Unauthorized access to IoT device!; sid:00000000;rev:003; )
and inside my Test folder the IoTProtect.rules file now only says:
sid:00000002
Sid replaced!
where I actually need IoTProtect.rules to say:
reject tcp any any -> 169.254.183.24 23 (msg:Unauthorized access to IoT device!; sid:00000002;rev:003; )
Apologies if my code is garbage but would I would really appreciate any advice or feedback on how to get this functionality working.
Thanks!
There are two problems in code:
1) use fileinput.Fileinput insted of fileinput.input
2) replace:
print(line.replace(line,new_text))
by:
print(line.replace(text,new_text))
UPDATE:
Your question is already answered Here
more info about string.replace()
Related
I have a question in regards to comparing files using python. For context, the problem I am having is that I have two firewalls with different configurations (over 14000 lines each on Notepad++) and I need to find the differences and annotate them.
Quick Example -
Firewall 1:
Version: 123
set policy EXPLICIT_DENY ALL
IP address allow 1.2.3.4
IP address allow 4.3.2.1
set policy EXPLICIT_ALLOW NONE
Firewall 2:
Version: 321
set policy EXPLICIT_ALLOW NONE
IP address allow 4.3.2.1
IP address allow 1.2.3.4
set policy EXPLICIT_DENY ALL
A line-by-line comparison would show that all of those lines are incorrect because they do not match side by side, however, the configuration is the same and would not need to be annotated. The only difference would be the Version # in the example. The script below was able to work for my purposes.
Current Script I ran -
'file1 = open("OLD FW.txt",'r')
'file2 = open("NEW FW.txt",'r')
'file3 = open("Results.txt",'r+')
'file1_lines = file1.readlines()
'file2_lines = file2.readlines()
'for position, a in enumerate(file1_lines):
'linematch = False
'for b in file2_lines:
'if a == b:
'linematch = True
'if linematch == False:
'file.3write(f"{position+1}: {a.strip()}\")
'file1.close()
'file2.close()'
The output would show every line from the OLD firewall that does not appear on the NEW firewall. This would effectively let me see what configurations are missing and/or different AND show me what line is is on the original FW.
The issue I figured out after coming up with this is that my current software version at work is only Python 2.7.16 which doesn't support f-strings. I did a little bit of research but am far to novice currently to figure this out in the short time window I have.
Mai question: How do I convert this Python f-string script to something that would work the same in an older version of Python that doesn't support f-strings?
Thanks in advance to anyone who can help me figure this out!
For simple cases like you show, you can use the .format() method.
file.write("{}: {}\n".format(position+1, a.strip()))
I'm trying to communicate with my mpu9250 through SPI using the py-spidev module and I'm unable to understand how exactly the read function works.
I found this function snippet that performs the read register function and I'd like to know why the __READ_FLAG (__READ_FLAG = 0x80) is concatenated with the address byte for sending the dummy values to. Won't this change the register address completely?
def ReadReg(self, reg_address):
self.bus.open(self.spi_bus_number, self.spi_dev_number)
tx = [reg_address | self.__READ_FLAG, 0x00]
rx = self.bus.xfer2(tx)
self.bus.close()
return rx[1]
Found the answer for this in another datasheet that follows the same protocol.
Writing is done by lowering CSB and sending pairs control bytes and register data. The control
bytes consist of the SPI register address (= full register address without bit 7) and the write
command (bit7 = RW = ‘0’). Several pairs can be written without raising CSB. The transaction is
ended by a raising CSB.
Reading is done by lowering CSB and first sending one control byte. The control bytes consist
of the SPI register address (= full register address without bit 7) and the read command (bit 7 =
RW = ‘1’). After writing the control byte, data is sent out of the SDO pin (SDI in 3-wire mode);
the register address is automatically incremented.
I am trying to create a List with regex in a Python shell.
In list I have 3 value topic-1, topic-2, topic-3. I am creating one consumer object which is having topic and topic should contains 3 values [topic1, topic2, topic3]. so Whenever I want to point any one from topic-1, topic-2, topic-3. so it should take a message from right topic.
I am following below code but it's giving one issue:
import pulsar
import re
client = pulsar.Client('pulsar://localhost:6650')
topic = 'my-topic'
topic = ['topic-1', 'topic-2', 'topic-3']
topic = re.compile('topic-.*')
print(topic)
# <_sre.SRE_Pattern object at 0x7f13314e7210>
consumer = client.subscribe(topic, "my-subscription")
2019-04-26 07:05:02.956 INFO ConnectionPool:72 | Created connection for
pulsar://localhost:6650
2019-04-26 07:05:02.957 INFO ClientConnection:300 | [127.0.0.1:55874 ->
127.0.0.1:6650] Connected to broker
Here I am able to create consumer object, But it's not creating with right value like [topic-1, topic-2, topic-3]
because in next step I am not able to receive the message.
What would be the syntax issue?
I can't find anything overtly wrong in your syntax. Are you sure you have those topics in your namespace? Try using pulsar's command line tools, e.g.:
pulsar-admin tenants list
pulsar-admin namespaces list <>
pulsar-admin topics list tenant/cluster/namespace
See here for more options: https://pulsar.apache.org/docs/latest/reference/CliTools/
I am trying to create a few inputs in LabVIEW 2016 which a user can modify (eg. total frames = 100). This number will then be sent to and RPi3 unit which is running a basic TCP/IP server script. The idea is that these numbers will set the variables in a simple instrument control code. I can connect to the RPi in LabVIEW and can send a string but things break down there:
-the string seems to be sent as Decimal ASCII
-when decoded in python, the string is converted so that every character is a separate element, with a separate index (eg. if I send 100 I get str[0]=1, str[1]=0, str[2]=0, len(str)=3)
-i need to send several variables and several commands in one string and then unpack it in python so that I can call each one separately and assign it to the appropriate function
Any advice would be appreciated.
I would personally just create a cluster of your paramters in labview, then use 'flatten to json' and you can simply decode that in python into a object with each of your variables inside it.
in python, you can then easily load that config data
import json
# sample string, replace this with received data from client/server comms
config = '{'total frames': 100, 'rate': 30, 'additional': 'whatever'}'
newconfig = json.loads(config)
print( list(newconfig) ) # list of all the tuples
# ['total frames', 'rate', 'additional']
# to access any tuple
num_frames = newconfig['total frames']
I hooked up the Keithley 2701 DMM, installed the software and set the IPs right. I can access and control the instrument via the internet explorer webpage and the Keithley communicator. When I try to use python, it detects the instrument
i.e. a=visa.instrument("COM1") doesn't give an error.
I can write to the instrument as well:
a.write("*RST")
a.write("DISP:ENAB ON/OFF")
a.write("DISP:TEXT:STAT ON/OFF")
etc all don't give any error but no change is seen on the instrument screen.
However when I try to read back, a.ask("*IDN?") etc give me an error
saying timeout expired before operation completed.
I tried redefining as:
a=visa.instrument("COM1",timeout=None)
a=visa.instrument("TCPIP::<the IP adress>::1354::SOCKET")
and a few other possible combinations but I'm getting the same error.
Please do help.
The issue with communicating to the 2701 might be an invalid termination character. By default the termination character has the value CR+LF which is “\r\n”.
The python code to set the termination character is:
theInstrument = visa.instrument(“TCPIP::<IPaddress>::1394::SOCKET”, term_chars = “\n”)
or
theInstrument = visa.instrument(“TCPIP::<IPaddress>::1394::SOCKET”)
theInstrument.term_chars = “\n”
I hope this helps,