[英]How do I change the hostname using Python on a Raspberry Pi
我嘗試使用(根據記憶,這可能不是 100% 准確):
import socket
socket.sethostname("NewHost")
我收到權限錯誤。
我將如何完全從 Python 程序中解決這個問題?
我想永久更改主機名,這需要在幾個地方進行更改,所以我制作了一個 shell 腳本:
#!/bin/bash
# /usr/sbin/change_hostname.sh - program to permanently change hostname. Permissions
# are set so that www-user can `sudo` this specific program.
# args:
# $1 - new hostname, should be a legal hostname
sed -i "s/$HOSTNAME/$1/g" /etc/hosts
echo $1 > /etc/hostname
/etc/init.d/hostname.sh
hostname $1 # this is to update the current hostname without restarting
在 Python 中,我使用subprocess.run運行腳本:
subprocess.run(
['sudo', '/usr/sbin/change_hostname.sh', newhostname])
這是從作為www-data
運行的網絡服務器發生的,所以我允許它在沒有密碼的情況下sudo
這個特定的腳本。 如果您以root
或類似身份運行,則可以跳過此步驟並在沒有sudo
的情況下運行腳本:
# /etc.d/sudoers.d/099-www-data-nopasswd-hostname
www-data ALL = (root) NOPASSWD: /usr/sbin/change_hostname.sh
這是一種不同的方法
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')
下次重新啟動時,主機名將設置為新名稱
如果您只需要在下次重新啟動之前更改主機名,許多 linux 系統可以更改它:
import subprocess
subprocess.call(['hostname', 'newhost'])
或者打字較少,但有一些潛在的陷阱:
import os
os.system('hostname %s' % 'newhost')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.