Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > replacing text inplace

Reply
Thread Tools

replacing text inplace

 
 
Matt Herzog
Guest
Posts: n/a
 
      04-20-2008
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Ann: InPlace, a new xslt-based CMS Oleg Paraschenko XML 0 10-04-2007 04:56 AM
gcc needs copy consturctor for inplace constructed object passed to func as reference, others not nutty C++ 6 06-15-2006 02:02 PM
asp 1.1 datagrid inplace editing, utf-8 code saved as "??" ? jason ASP .Net 0 11-09-2005 06:57 AM
DataGrid InPlace Editing msnews.microsoft.com ASP .Net 0 01-29-2005 10:11 AM
inplace edit error message news.verizon.net Perl 4 10-08-2003 09:43 PM



Advertisments