How to change hostname in CentOS

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


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 :

'''Change System Hostname
usage : chostname
Created by Dhika Cikul'''

import os,sys,syslog

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

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

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

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

#Write to configuration file
setHostFile = open(hostnameConfig,'w')

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

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


Incoming search terms:

dhika | python set hostname | 

Comments posted (3)

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

# hostname

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


That change is permanent, if you use

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

Write a comment