0

I have trawled this site for years and have always found my answer but today I was unsuccessful. I am tasked with writing a python script that can search, add and delete host from a dhcp.conf file. i.e.

host testnode{
    option host-name "testnode";
    option root-path "0.0.0.0:/foo/bar/foobar/testnode";
    option subnet-mask 0.0.0.0;
    option routers 0.0.0.0;
    hardware ethernet 00:00:00:00:00:00;
    fixed-address 0.0.0.0;

}

In the above format. I can search the dhcp.conf file using re.search(str, line) to find testnode, but how do I get me code to print out every line from testnode until the ending "}"?

This is the code I have up to now.

   #!/usr/bin/env python
    import re
    infile = open('/etc/dhcp/dhcpd.conf', 'r')
    str = raw_input('Enter hostname to search: ');
    def search_host( str ):
        for line in infile:
                if re.search(str, line):
                    print line
                    while (line != '^}'):
                       line = next(infile)
                       print line
search_host(str);

re.search will stop at testnode then code prints out every line in the dhcp.conf file until it hits the end. How to tell the while loop to stop once it hits the "}" at the end of the host entry.

Thanks

2
  • line != '^}' is looking for a line of text which exactly contains the charactesr ^ and }. it's not a regex, just a plain string comparison, therefore the regex metachars are NOT metachars, just plain text throwing off your matches. Commented Mar 10, 2015 at 21:11
  • I haven't used it, but have you tried pypi.python.org/pypi/iscconf? Commented Mar 10, 2015 at 21:21

1 Answer 1

1

Code below will print everything after your first match and break out when it encounters a '}'. No need to use a while and interfere with the file object's iteration.

infile = '/etc/dhcp/dhcpd.conf'
str = raw_input('Enter hostname to search: ');
def search_host( str, infile):
    start = False
    with open(infile, 'r') as f:
        for line in f:
            if re.search(str, line):
                start = True
            if start:
                print line
                if re.search('}', line):
                    break
search_host(str, infile);
Sign up to request clarification or add additional context in comments.

3 Comments

I had to modify the code a little but it work. I had to encapsulate the last if with in the if start.
I edited the answer. Please select it as an answer if it solved your problem
How do I select it as an answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.