replacing text inplace

Discussion in 'Python' started by Matt Herzog, Apr 21, 2008.

  1. Matt Herzog

    Matt Herzog Guest

    Hey All.

    I'm learning some python with the seemingly simple task of updating a firewall config file with the new IP address when my dhcpd server hands one out. Yeah, I know it's dangerous to edit such a file "in place" but this is just an exercise at this point. I would not mind using file handles except they seem to add complexity.

    The only apparent problem I have with my script so far is that it's adding lots of blank lines to the file when it updates the IP addresses.

    There is only one dotted quad that needs changing in a file full of dotted quads and the dhcp lease lasts for months usually so I have no qualms about putting the old IP address in the file, i.e. I won't need to manually update it very often. The address apears on lines that looks like this:

    block in from 71.146.250.258/32 to any group 150

    So "71.146.250.258" needs to change to "71.146.250.223" or something similar.

    Is there a saner, cleaner way to do this that won't add new, blank lines?
    Most of the examples on the Intertubes are about multiple files and STDIN.
    This is just one file and it needs one string changed on two or three lines.
    The script runs from cron, not interactively.

    ###########################################################################

    import sys
    import string
    import os
    import fileinput
    import re

    oldip = "71.146.250.258"

    ifcfg_lines = os.popen("/sbin/ifconfig eth0").readlines()
    newip = string.split(ifcfg_lines[1])[1][-11:]

    if newip == oldip:

    print "nevermind"

    else:

    for line in fileinput.FileInput("/etc/ipf.conf",inplace=1):
    line = line.replace(oldip,newip)
    print line

    --
    "Outside of a dog, a book is a man's best friend. Inside of a dog, it is too dark to read."
    -- Groucho Marx
    Matt Herzog, Apr 21, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. news.verizon.net

    inplace edit error message

    news.verizon.net, Sep 29, 2003, in forum: Perl
    Replies:
    4
    Views:
    1,597
    Jim Gibson
    Oct 8, 2003
  2. msnews.microsoft.com

    DataGrid InPlace Editing

    msnews.microsoft.com, Jan 29, 2005, in forum: ASP .Net
    Replies:
    0
    Views:
    342
    msnews.microsoft.com
    Jan 29, 2005
  3. jason
    Replies:
    0
    Views:
    416
    jason
    Nov 9, 2005
  4. nutty
    Replies:
    6
    Views:
    387
    Tom Widmer
    Jun 15, 2006
  5. Oleg Paraschenko

    Ann: InPlace, a new xslt-based CMS

    Oleg Paraschenko, Oct 4, 2007, in forum: XML
    Replies:
    0
    Views:
    440
    Oleg Paraschenko
    Oct 4, 2007
Loading...

Share This Page