0

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!

WSMathias9
  • 669
  • 8
  • 15
George Rees
  • 33
  • 2
  • 9
  • 2
    The `print(line.replace(line,new_text))` does not have any effect on the `line` variable, much less on the line in the actual file. You just create a new string with that part being replaced. – tobias_k Feb 13 '18 at 11:57
  • 1
    you are going to have a problem with `new_text = "sid:0000000{}".format(added)` when you incr to 10 and above you can use `"{:<03}".format` for adding zeros I didn't understand your problem yet, can you be clearer – shahaf Feb 13 '18 at 12:02
  • Possible duplicate of [How to search and replace text in a file using Python?](https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file-using-python) – WSMathias9 Feb 14 '18 at 07:16

1 Answers1

0

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()

WSMathias9
  • 669
  • 8
  • 15