搞这个脚本的目的:因为yahoo目录严格地遵守开发、测试、生产环境三条线的方针,所以我经常需要设置hosts文件,在各种环境中倒来倒去,手动修改hosts文件,非常麻烦。所以,决定搞一个脚本来管理一下. 用法: a:我要测试了,所以切换到testing环境。运行hosts test.马上就好了。 b:我要添加几个testing 环境的hosts ,运行hosts edit test 具体步骤: 1.建这样一个文件: #! /usr/bin/ruby subcmd=ARGV.shift DATADIR=”/home/renlu/bin/hostsdata/“ HOSTFILE=”/etc/hosts” # load the yaml file to a variable require “yaml” def init(env) data=Hash.new open(DATADIR+env+”.yaml”,”w”) do |f| f.write(YAML.dump(data)) end end def firstboot init(“dev”) init(“test”) init(“online”) end def quit(cmd) if cmd =~ /exit|eixt|quit|qt/ then exit(0) end end def switch(env) data=load(env) string=”” data.each{ |domain,ip| string = string + “#{ip} #{domain}n” } open(DATADIR + “pre”) do |f| string = f.read + string end open(HOSTFILE ,”w”) do |f| f.write(string) end print string+”n” end def load(env) data=Hash.new open(DATADIR + env+”.yaml”) do |f| data=YAML.load(f) end data end #write the hash as yaml to a file def save(env,data) open(DATADIR+env+”.yaml”,”w”) do |f| f.write(YAML.dump(data)) end end def cat() cmd2=ARGV.shift if cmd2 =~ /dev/ then env=”dev” elsif cmd2 =~ /online|ol/ then env=”online” elsif cmd2 =~ /test/ then env=”test” end data=load(env) puts data end def usage print “ Yet a simple hosts manager version 0.1 Author :renlu.xu URL :http://www.162cm.com/ usage : hosts dev —- switch to dev environment hosts test —- switch to testing environment hosts online —- switch to online environment hosts add dev —- edit a domain for dev|online|test environment hosts add dev —- the same with ‘hosts add dev’ Notice: dev means Development test means Testing online|ol means testing if you input Quit|exit, We asumed that you want to exit. When you use this program first time,Run ‘hosts first ‘ and then initialze the data files’ “ end def edit() cmd2=ARGV.shift if cmd2 =~ /dev/ then env=”dev” elsif cmd2 =~ /online|ol/ then env=”online” elsif cmd2 =~ /test/ then env=”test” end print “input the domain:(such as www.sina.com)n" domain=gets.chomp quit(domain) print “input the ip:(127.0.0.1 and so on…n” ip=gets.chomp quit(ip) data=load(env) data[domain]=ip save(env,data) switch(env) end quit(subcmd) if subcmd =~ /first/ then firstboot elsif subcmd =~ /ls|view|cat/ then cat elsif subcmd =~ /edit|add/ then edit elsif subcmd =~ /dev/ then switch “dev” elsif subcmd =~ /test/ then switch “test” elsif subcmd =~ /online|ol/ then switch “online” else usage end 呵呵。头几行有个设置,一个是hosts文件的地址,一个是存储数据文件的目录。根据你的需要来设置。 3: 建立那个存储你的各位环境hosts信息的目录。 4 Enjoy the script. 5:如果在是linux环境下,你需要给这个脚本设置访问/etc/hosts的权限: #sudo chown root:root hosts #sudo chmod +s hosts 这样,这个脚本就自然而然地拥有了root用户的权限。也就是说,一个普通用户也能通过这个脚本去修改hosts文件。