I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.
Create variable LASTKNOWN = "212.171.135.53" This is the ip address we have while writing this script.
Get the current IP address. It will change on a daily basis.
Create variable CURRENT for the new IP.
Compare (as strings) CURRENT to LASTKNOWN
If they are the same, exit()
If they differ,
A. "Copy" the old config file (/etc/ipf.conf) containing LASTKNOWN IP address into /tmp
B. Replace LASTKNOWN with CURRENT in the /tmp/ipf.conf file.
C. Using subprocess "mv /tmp/ipf.conf /etc/ipf.conf"
D. Using subprocess execute, "ipf -Fa -f /etc/ipf.conf"
E. Using subprocess execute, "ipnat -CF -f /etc/ipnat.conf"
exit()
I know how to do steps 1 through 6. I fall down on the "file editing" part, A -> C. I can't tell what module to use or whether I should be editing the file in place. There are so many ways to do this, I can't decide on the best approach. I guess I want the most conservative one.
I know how to use subprocess, so you don't need to comment on that.
I don't want to replace entire lines; just a specific dotted quad.
Thanks!
Another way to simply edit files in place is to use the fileinput
module:
import fileinput, sys
for line in fileinput.input(["test.txt"], inplace=True):
line = line.replace("car", "truck")
# sys.stdout is redirected to the file
sys.stdout.write(line)
filename = "/etc/ipf.conf"
text = open(filename).read()
open(filename, "w").write(text.replace(LASTKNOWN, CURRENT))
from __future__ import with_statement
from contextlib import nested
in_filename, outfilename = "/etc/ipf.conf", "/tmp/ipf.conf"
with nested(open(in_filename), open(outfilename, "w")) as in_, out:
for line in in_:
out.write(line.replace(LASTKNOWN, CURRENT))
os.rename(outfilename, in_filename)
Note: "/tmp/ipf.conf" should be replaced by tempfile.NamedTemporaryFile()
or similar
Note: the code is not tested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With