
我必須透過 Fedora 19 機器中的各種網路代理來檢查網站效能,並且我想透過將本機可解析名稱「代理」設定為檔案中代理程式的 DNS 解析名稱來實現此目的/etc/hosts
。因此,/etc/hosts
文件的內容應如下所示:
proxy.us.company.com proxy
#proxy.eu.company.com proxy
#proxy.sa.company.com proxy
然後,當我需要測試不同的代理程式時,我只需編輯該/etc/hosts
檔案並取消註釋不同的代理 DNS 名稱,我的所有登入(以及使用我的電腦的其他人)都將根據新代理進行檢查。上述大多數 DNS 名稱都是循環條目,這也很好,並且是我的測試所必需的。 (說實話,我在實際工作中也需要這個,因為 proxy.us 偶爾會陷入困境,而其他代理之一最終會比 proxy.us 更快。)
我該怎麼做呢?我確實考慮編寫一個腳本來更改http_proxy
env 變量,但使用該方法,我需要向每個進程添加一個額外的步驟,以將所有登入變數對齊在一起。我只想在一個地方改變它。/etc/hosts
似乎是進行系統範圍名稱解析更改的最合乎邏輯的地方。
答案1
/etc/hosts 僅將名稱對應到 IP 位址。
您仍然可以使用 /etc/hosts,但您必須編寫腳本將名稱解析為 IP 並使用該 IP 修改 /etc/hosts,或提前完成工作,建立多個主機檔案並讓您的腳本簡單地移動在檢查的正確位置為每個代理程式放置檔案。
答案2
這是不可能的。執行我想要的操作的最佳解決方案是安裝名稱解析器(綁定、命名)並使用代理程式的 FQDN 更新其本機表。
答案3
這是一個可以完成您想要的操作的 python 腳本:
#!/usr/bin/env python
from dns.resolver import Resolver
from re import sub
hostsfile='/etc/hosts'
proxies = [
'proxy.us.company.com',
'proxy.eu.company.com',
'proxy.sa.company.com'
]
name = 'proxy'
def main():
proxy = menu('Select proxy:', proxies)
ip = Resolver().query(proxy,'A')[0].to_text()
if len(ip):
with open(hostsfile, 'r') as h:
hosts = h.read()
with open(hostsfile, 'w+') as h:
hosts = sub('((\n|(?<!\n)\.)(1?\d?\d|2[0-4]\d|25[0-5])){4} +'+name+'(?= *\n)', '\n'+ip+' '+name, hosts)
h.write(hosts)
def getInt(question, min, max):
min,max = [int(max),int(min)] if min>max else [int(min),int(max)]
while True:
try:
answer = int(raw_input('{0}: '.format(question)))
if min <= answer <= max:
return answer
print('Must be a number from {0} to {1}'.format(min,max))
except ValueError:
print('Not a valid number')
def menu(title, items, index=False):
print(title)
for i, item in enumerate(items):
print('{0}. {1}'.format(i+1, item))
answer = getInt('', 1, len(items)) - 1
return answer if index else items[answer]
main()