【问题标题】:How do I replace a hostname in /etc/hosts on debian with Python如何用 Python 替换 debian 上的 /etc/hosts 中的主机名
【发布时间】:2012-11-13 18:02:23
【问题描述】:

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

  • 从 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')

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

【问题讨论】:

  • 这些与 Linux 中操作系统配置文件的交互对于使用 sedbash(shell)脚本来说是一个很好的用例,如果您想尝试的话。您遇到了什么错误,或者应该是什么没有发生?
  • 为什么不使用主机名可执行文件?
  • 您可能必须读取所有文件内容并替换您想要的位。应该没那么难。

标签: python ubuntu debian hostname


【解决方案1】:

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

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 命令。

【讨论】:

  • seek(0) 被发现是我的问题。据我所知,它适用于 /etc/hostname,但不适用于 /etc/hosts。
  • replace() 不会就地修改字符串。您必须将其重新分配给变量:contents = contents.replace(old,new)
【解决方案2】:

使用域更改主机名的 Python 函数 您需要一个名为 hosts_tail 的帮助文件,位于文件系统中的任何位置:

帮助文件 hosts_tail

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Python 函数:

def set_hostname(hostname,domain):
"""
usage: set_hostname('debian','labor.local')
"""
try:
    os.system('echo 127.0.0.1    localhost > /etc/hosts')
    os.system('echo 127.0.1.1    '+ hostname + '.' + domain + ' ' + hostname +  ' >> /etc/hosts')
    os.system('cat ' + mypath + 'config/hosts_tail >> /etc/hosts')
    os.system('echo ' + hostname + ' > /etc/hostname')
    os.system('echo ' + hostname + '.' + domain + ' > /etc/mailname')
    os.system('cat /etc/resolv.conf | grep nameserver | uniq > /tmp/resolv.tmp')
    os.system("echo domain " + domain + ' > /etc/resolv.conf')
    os.system("echo search " + domain + ' >> /etc/resolv.conf')
    os.system('cat /tmp/resolv.tmp | uniq >> /etc/resolv.conf')
    os.system('rm -rf /tmp/resolv.tmp')
    os.system('/etc/init.d/hostname.sh start')
except Exception, e:
    return False
return True

我的 debian 操作系统:

cat /etc/debian_version
6.0.6

【讨论】:

  • 您的第一个os.system 调用会覆盖主机文件。所有条目都需要在您的 hosts_tail 文件中复制或通过调用您的函数来删除。此外,捕获所有异常似乎很糟糕:如果函数被部分执行,它可能会使系统处于不一致的状态 - 在这种情况下,我想要的信息不仅仅是 False :) 例如,您的代码没有定义 @ 987654326@任何地方;像这样运行它总是会返回False,因为UnboundLocalError
猜你喜欢
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 2011-07-05
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
相关资源
最近更新 更多