I'm scripting a way to set hostname on a Debian system with Python. I succeed at:
- getting the new hostname from arg1 or if I define it as the value of a variable
- get the current hostname
- open
/etc/hostname
and write the new hostname from the variable to the file and subsequently close it. - open
/etc/hosts
for reading or writing
I get stuck there. I've tried reading it as a string to do str.replace(oldname, newname)
, but run into trouble unless I turn the file contents into str
. If I do that, I can't write the file.
Alternatively, I've tried re.sub()
, but likewise have trouble writing the results to /etc/hosts
.
Any feedback is appreciated.
I did research examples and found a solution for CentOS. I've learned from it, but don't see a solution to my problem.
Bash is absolutely the right tool for this job. 3 lines if I don't concatenate. I need a python solution, however.
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.
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:
#!/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')
I then will hope to write a single function to write/replace the new hostname where the old hostname was.