如何在Raspberry Pi上使用Python更改主机名
我尝试使用(根据记忆,这可能不是100%准确): 我有一个权限错误如何在Raspberry Pi上使用Python更改主机名,python,Python,我尝试使用(根据记忆,这可能不是100%准确): 我有一个权限错误 如何从Python程序中完全实现这一点?如果您只需要在下次重新启动之前更改主机名,许多linux系统可以通过以下方式进行更改: import subprocess subprocess.call(['hostname', 'newhost']) 或者输入较少但存在一些潜在缺陷: import os os.system('hostname %s' % 'newhost') 我想永久更改主机名,这需要在几个地方进行更改,因此我制
如何从Python程序中完全实现这一点?如果您只需要在下次重新启动之前更改主机名,许多linux系统可以通过以下方式进行更改:
import subprocess
subprocess.call(['hostname', 'newhost'])
或者输入较少但存在一些潜在缺陷:
import os
os.system('hostname %s' % 'newhost')
我想永久更改主机名,这需要在几个地方进行更改,因此我制作了一个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中,我使用以下命令运行脚本:
这是在一个运行为www-data
的Web服务器上发生的,因此我允许它在没有密码的情况下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')
下次重新启动时,主机名将设置为新名称
# /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')