我尝试过使用(从内存来看,这可能不是100%准确):
import socket
socket.sethostname("NewHost")
我收到了权限错误。
我将如何从Python程序中完全解决这个问题?
答案 0 :(得分:2)
我想永久更改主机名,这需要在几个地方进行更改,所以我制作了一个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
这个特定的脚本。如果您以sudo
或类似方式运行,则可以跳过此步骤并在不使用root
的情况下运行脚本:
# /etc.d/sudoers.d/099-www-data-nopasswd-hostname
www-data ALL = (root) NOPASSWD: /usr/sbin/change_hostname.sh
答案 1 :(得分:0)
如果您只需要在下次重启之前更改主机名,许多linux系统都可以通过以下方式更改主机名:
import subprocess
subprocess.call(['hostname', 'newhost'])
或打字较少但有一些潜在的陷阱:
import os
os.system('hostname %s' % 'newhost')
答案 2 :(得分:0)
这是另一种方法
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')
下次重启时,主机名将被设置为新名称