title: How do I replace a hostname in /etc/hosts on debian with Python
body: <p>I'm scripting a way to set hostname on a Debian system with Python. I succeed at:</p>
  
  <ul>
  <li>getting the new hostname from arg1 or if I define it as the value of a variable</li>
  <li>get the current hostname</li>
  <li>open <code>/etc/hostname</code> and write the new hostname from the variable to the file and subsequently close it.</li>
  <li>open <code>/etc/hosts</code> for reading or writing</li>
  </ul>
  
  <p>I get stuck there. I've tried reading it as a string to do <code>str.replace(oldname, newname)</code>, but run into trouble unless I turn the file contents into <code>str</code>. If I do that, I can't write the file.</p>
  
  <p>Alternatively, I've tried <code>re.sub()</code>, but likewise have trouble writing the results to <code>/etc/hosts</code>.</p>
  
  <p>Any feedback is appreciated.</p>
  
  <p>I did research examples and found <a href="http://dhika.cikul.or.id/how-to-change-hostname-in-centos.html" rel="nofollow">a solution for CentOS</a>. I've learned from it, but don't see a solution to my problem.</p>
  
  <p>Bash is absolutely the right tool for this job. 3 lines if I don't concatenate. I need a python solution, however.</p>
  
  <p>The code cited above writes to hostname: I've that taken care of that. I'm not finding that the same strategy works with hosts.</p>
  
  <p>Here's working code, thanks for suggestions. They need to be taken into account. I've also left off the conclusion. But this does the narrowly defined job:</p>
  
  <pre><code>#!/usr/bin/python -ex
  import os, sys, syslog
  
  #Customize
  hosts_file = '/etc/hosts'
  hostname_file = '/etc/hostname'
  
  #Check for root
  if not os.geteuid()==0:
      sys.exit("\nOnly root can run this script\n")
  
  if len(sys.argv) != 2:
      print "Usage: "+sys.argv[0]+" new_hostname"
      sys.exit(1)
  
  new_hostname = sys.argv[1]
  
  print 'New Hostname: ' +new_hostname
  
  #get old hostname
  f_hostname = open('/etc/hostname', 'r')
  old_hostname = f_hostname.readline()
  old_hostname = old_hostname.replace('/n','')
  f_hostname.close()
  
  print 'Old Hostname: ' +old_hostname
  
  #open hosts configuration
  f_hosts_file = open(hosts_file, 'r')
  set_host = f_hosts_file.read()
  f_hosts_file.close()
  pointer_hostname = set_host.find(old_hostname)
  
  #replace hostname in hosts_file
  set_host = set_host.replace(old_hostname, new_hostname)
  set_host_file = open(hosts_file,'w')
  set_host_file.seek(pointer_hostname)
  set_host_file.write(set_host)
  set_host_file.close()
  
  #insert code to handle /etc/hostname
  
  #change this system hostname
  os.system('/bin/hostname '+new_hostname)
  
  #write syslog
  syslog.syslog('CP : Change Server Hostname')
  </code></pre>
  
  <p>I then will hope to write a single function to write/replace the new hostname where the old hostname was.</p>