how to change pi hostname in python file 1

how to change pi hostname in python file

    import os
    def setHostname(newhostname):
        with open('/etc/hosts', 'r') as file:
        # read a list of lines into data
        data = file.readlines()

        # the host name is on the 6th line following the IP address
        # so this replaces that line with the new hostname
        data[5] = '127.0.1.1       ' + newhostname

        # save the file temporarily because /etc/hosts is protected
        with open('temp.txt', 'w') as file:
            file.writelines( data )

        # use sudo command to overwrite the protected file
        os.system('sudo mv temp.txt /etc/hosts')

        # repeat process with other file
        with open('/etc/hostname', 'r') as file:
            data = file.readlines()

        data[0] = newhostname

        with open('temp.txt', 'w') as file:
            file.writelines( data )

        os.system('sudo mv temp.txt /etc/hostname')

    #Then call the def
    setHostname('whatever')

Here is what the above code is Doing:
1. Open the file /etc/hosts and read it into a list called data.
2. Replace the 6th line of data with the new hostname.
3. Write the new data to a temporary file.
4. Use the sudo command to move the temporary file to /etc/hosts.
5. Repeat the process with the file /etc/hostname.

Similar Posts