gpt4 book ai didi

python - 如何用 Python 替换 debian 上/etc/hosts 中的主机名

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:35 25 4
gpt4 key购买 nike

我正在编写一种使用 Python 在 Debian 系统上设置主机名的方法。我成功了:

  • 从 arg1 获取新的主机名,或者如果我将其定义为变量的值
  • 获取当前主机名
  • 打开 /etc/hostname 并将变量中的新主机名写入文件,然后将其关闭。
  • 打开/etc/hosts进行读写

我卡在那里了。我尝试将其作为字符串读取以执行 str.replace(oldname, newname),但遇到麻烦除非我将文件内容转换为 str。如果这样做,我将无法写入文件。

或者,我试过 re.sub(),但同样无法将结果写入 /etc/hosts

欢迎任何反馈。

我研究了示例并找到了 a solution for CentOS .我从中吸取了教训,但看不到我的问题的解决方案。

Bash 绝对是完成这项工作的合适工具。如果我不连接,则为 3 行。但是,我需要一个 Python 解决方案。

上面引用的代码写入主机名:我已经处理好了。我没有发现同样的策略适用于主机。

这是工作代码,感谢您的建议。他们需要被考虑在内。我也放弃了结论。但这是狭义定义的工作:

#!/usr/bin/python -ex
import os, sys, syslog

#Customize
hosts_file = '/etc/hosts'
hostname_file = '/etc/hostname'

#Check for root
if not os.geteuid()==0:
sys.exit("\nOnly root can run this script\n")

if len(sys.argv) != 2:
print "Usage: "+sys.argv[0]+" new_hostname"
sys.exit(1)

new_hostname = sys.argv[1]

print 'New Hostname: ' +new_hostname

#get old hostname
f_hostname = open('/etc/hostname', 'r')
old_hostname = f_hostname.readline()
old_hostname = old_hostname.replace('/n','')
f_hostname.close()

print 'Old Hostname: ' +old_hostname

#open hosts configuration
f_hosts_file = open(hosts_file, 'r')
set_host = f_hosts_file.read()
f_hosts_file.close()
pointer_hostname = set_host.find(old_hostname)

#replace hostname in hosts_file
set_host = set_host.replace(old_hostname, new_hostname)
set_host_file = open(hosts_file,'w')
set_host_file.seek(pointer_hostname)
set_host_file.write(set_host)
set_host_file.close()

#insert code to handle /etc/hostname

#change this system hostname
os.system('/bin/hostname '+new_hostname)

#write syslog
syslog.syslog('CP : Change Server Hostname')

然后我希望编写一个函数来写入/替换旧主机名所在的新主机名。

最佳答案

您提供的链接打开主机文件进行读取,将其内容保存在一个字符串中,调用字符串上的替换,关闭文件,打开文件进行写入并写入字符串 - 这到底是不是您的解决方案问题?

f = open("/etc/hosts", "r")     #open file for reading
contents = f.read() #read contents
f.close() #close file
contents.replace(old, new) #replace
f = open("/etc/hosts", "w") #open file for writing
f.write(contents) #write the altered contents
f.close() #close file

您也可以使用 r+ 模式在不关闭并重新打开文件的情况下执行此操作:

f = open("/etc/hosts", "r+")    #open file with mode r+ for reading and writing
contents = f.read() #read the file
contents.replace(old, new) #replace
f.seek(0) #reset the file pointer to the start of the file
f.truncate() #delete everything after the file pointer
f.write(contents) #write the contents back
f.close() #close the file

请注意,如果您不采取特殊预防措施,使用 replace 是不安全的 - 例如主机名可能是主机文件中包含的其他主机名或别名的子字符串,因此您至少应该做的是在替换之前用空格将其包围。您还需要确保输入的任何内容作为主机名都是有效的。处理所有这些问题的最简单方法可能是通过 subprocess.Popen 调用操作系统的内置 hostname 命令。

关于python - 如何用 Python 替换 debian 上/etc/hosts 中的主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13366137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com