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

时间:2012-11-13 18:02:23

标签: python ubuntu debian hostname

我正在编写一种使用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')

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

2 个答案:

答案 0 :(得分: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是不安全的,例如:主机名可能是hosts文件中包含的其他主机名或别名的子字符串,因此您应该做的最少的事情是在替换之前用空格包围它。您还需要确保输入的内容甚至可以作为主机名有效。处理所有这些问题的最简单方法可能就是调用操作系统'通过hostname内置subprocess.Popen命令。

答案 1 :(得分:0)

用于更改域名的主机名的Python函数 你需要在你的filesytem中的任何地方找到一个名为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 os:

cat /etc/debian_version
6.0.6