daily pastebin goal
18%
SHARE
TWEET

Untitled

a guest Apr 17th, 2018 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import fileinput, sys
  2. for line in fileinput.input(["test.txt"], inplace=True):
  3.     line = line.replace("car", "truck")
  4.     # sys.stdout is redirected to the file
  5.     sys.stdout.write(line)
  6.    
  7. filename = "/etc/ipf.conf"
  8. text = open(filename).read()
  9. open(filename, "w").write(text.replace(LASTKNOWN, CURRENT))
  10.    
  11. from __future__ import with_statement
  12. from contextlib import nested
  13.  
  14. in_filename, outfilename = "/etc/ipf.conf", "/tmp/ipf.conf"
  15. with nested(open(in_filename), open(outfilename, "w")) as in_, out:
  16.      for line in in_:
  17.          out.write(line.replace(LASTKNOWN, CURRENT))
  18. os.rename(outfilename, in_filename)
  19.    
  20. f = open(filename, "r")
  21. lines = f.readlines()
  22.  
  23. # Assume that change_ip is a function that takes a string and returns a new one with the ip changed): example below
  24. ret_lines = [change_ip(lines) for line in lines]
  25. new_file = open(new_filename, "w")
  26. new_file.writelines(lines)
  27.  
  28. def change_ip(str):
  29.    ''' Gets a string, returns a new string where the ip is changed '''
  30.    # Add implementation, something like: return str.replace(old_ip, new_ip) or something similair.
  31.    
  32. Simply a test file 175.48.204.168
  33.  
  34. And two times 175.48.204.168 on this line 175.48.204.168
  35.  
  36. Done.
  37.    
  38. Simply a test file 10.73.144.112
  39.  
  40. And two times 10.73.144.112 on this line 10.73.144.112
  41.  
  42. Done.
  43.    
  44. import socket
  45. import fileinput
  46. import subprocess
  47. import string
  48. import re
  49.  
  50. CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0]
  51. LASTKNOWN = '175.48.204.168'
  52.  
  53. if CURRENT == LASTKNOWN:
  54.     print 'Nevermind.'
  55.     subprocess.sys.exit()
  56.  
  57. else:
  58.  
  59.     cf = open("/tmp/iiiipf.conf", "r")
  60.     lns = cf.readlines()
  61.     # close it so that we can open for writing later
  62.     cf.close()
  63.  
  64.     # assumes LASTKNOWN and CURRENT are strings with dotted notation IP addresses
  65.     lns = "".join(lns)
  66.     lns = re.sub(LASTKNOWN, CURRENT, lns)  # This replaces all occurences of LASTKNOWN with CURRENT
  67.  
  68.     cf = open("/tmp/iiiipf.conf", "w")
  69.     cf.write(lns)
  70.     cf.close()
  71.    
  72. import in_place
  73.  
  74. with in_place.InPlace('data.txt') as file:
  75.     for line in file:
  76.         line = line.replace('test', 'testZ')
  77.         file.write(line)
RAW Paste Data
Top