How to change hostname in CentOS

Posted by cikul | Posted in Linux, Python | Posted on 11-01-2007-05-2008

3

CentOS was popular linux distribution which based on RedHat. All of Dutahost Server use CentOS for production server.

How to change hostname in CentOS and how to build Python script to handle this?

  1. Open file /etc/sysconfig/network
  2. change hostname with your preferred hostname
  3. save the file and try to reboot to check if your hostname changed was sucessfull

Can be translated at Python :

#!/usr/bin/python
'''Change System Hostname
usage : chostname
Created by Dhika Cikul
dhika@cikul.or.id'''

import os,sys,syslog

if len(sys.argv) != 2:
print "Usage: "+sys.argv[0]+" new_hostname"
sys.exit(1)

newHostname = sys.argv[1]

#Get Old Hostname
fOldHost = os.popen('/bin/hostname','r')
oldHost = fOldHost.readline()
oldHost = oldHost.replace('\n','')
print 'Old Hostname : '+oldHost
print 'New Hostname : '+newHostname
fOldHost.close()

#Open Hostname Configuration
#hostnameConfig = 'network'
hostnameConfig = '/etc/sysconfig/network'
setHostFile = open(hostnameConfig,'r')
setHost = setHostFile.read()
setHostFile.close()

#Find oldHostname
pointerHostName = setHost.find(oldHost)
#Replace with new Host
setHost = setHost.replace(oldHost,newHostname)

#Write to configuration file
setHostFile = open(hostnameConfig,'w')
setHostFile.seek(0)
setHostFile.write(setHost)
setHostFile.close()

#change this system hostname
os.system('/bin/hostname '+newHostname)

#write syslog
syslog.syslog('CP : Change Server Hostname')

Done…

Incoming search terms:

dhika | python set hostname | 

Share and Enjoy

Comments posted (3)

If you want to make the change effective immediately (instead of rebooting), use the hostname command:

# hostname mybox.mydomain.com

[…] tis maar een idee.. Zie hier een link, mijn exacte zoekterm in google: centos hostname change http://dhika.cikul.or.id/2007/01/11/…name-in-centos __________________ Hosting met de beste service? Vertixo Hosting Solutions info{@}vertixo{dot}com […]

bvankuik,

That change is permanent, if you use
#hostname mybox.mydomain.com

while you restarted your box, your hostname will be back to your old hostname.

Write a comment

*