1 import os
2 def setHostname(newhostname):
3 with open('/etc/hosts', 'r') as file:
4 # read a list of lines into data
5 data = file.readlines()
6
7 # the host name is on the 6th line following the IP address
8 # so this replaces that line with the new hostname
9 data[5] = '127.0.1.1 ' + newhostname
10
11 # save the file temporarily because /etc/hosts is protected
12 with open('temp.txt', 'w') as file:
13 file.writelines( data )
14
15 # use sudo command to overwrite the protected file
16 os.system('sudo mv temp.txt /etc/hosts')
17
18 # repeat process with other file
19 with open('/etc/hostname', 'r') as file:
20 data = file.readlines()
21
22 data[0] = newhostname
23
24 with open('temp.txt', 'w') as file:
25 file.writelines( data )
26
27 os.system('sudo mv temp.txt /etc/hostname')
28
29 #Then call the def
30 setHostname('whatever')
31