2014-03-31 56 views
1

我有虛擬服務器啓動過程,我需要實施和過程中的一種需要在新推出的情況下產生的SSH密鑰被添加到部署服務器「的authorized_keys」文件。Python的請求「最大重試次數超過了與URL」錯誤

爲了做到這一點我創建了一個簡單的燒瓶的應用程序,將監聽與它的密鑰將被添加到authorized_keys中實例的IP和端口號在部署服務器傳入的GET請求。

這裏是瓶的應用程序,將在部署服務器上:

from flask import Flask, render_template 
import requests 
import os 
from time import sleep 

app = Flask(__name__) 


#Get the ip and port number from the newly launched port 
@app.route('/<ip_addr>/<port>') 
def get_ip_port(ip_addr, port): 

    #rmt_response = requests.get('http://%s:%s/id_rsa.pub' % (ip_addr, port)) 
    rmt_response = requests.get('http://127.0.1.1:9090/id_rsa.pub', timeout=1) 
    #sleep(5) 
    if rmt_response.status_code == 200: 
     auth_file = open("authorized_keys", "a") 
     auth_file.write(rmt_response.content) 
     return render_template('layout.html', ip_addr=ip_addr, port=port, \ 
          srvrsp=rmt_response.content, rmt_response=rmt_response) 
    else: 
     return render_template('layout.html', rmt_response=rmt_response) 


if __name__ == '__main__': 
    app.run(debug=True) 

這裏是將要在新的服務器實例啓動的Python應用程序

import sys, socket 
import BaseHTTPServer 
from SimpleHTTPServer import SimpleHTTPRequestHandler 
import requests 

HandlerClass = SimpleHTTPRequestHandler 
ServerClass = BaseHTTPServer.HTTPServer 
Protocol = "HTTP/1.0" 



local_ip = socket.gethostbyname(socket.gethostname()) 

if sys.argv[1:]: 
    port = int(sys.argv[1]) 
else: 
    port = 9090 

#Send the ip and the port num to deployment host 
r = requests.get("http://127.0.0.1:5000/%s/%s"%(local_ip,port)) 
#For debug only 
rtext = "http://127.0.0.1:5000/%s/%s"%(local_ip,port) 
server_address=(local_ip, port) 

HandlerClass.protocol_version = Protocol 
httpd = ServerClass(server_address, HandlerClass) 

sa = httpd.socket.getsockname() 
print "Serving HTTP on", sa[0], "port", sa[1], "..." 
print local_ip 
print r 
print rtext 
httpd.serve_forever() 

當我運行instace代碼(上面)並通過瀏覽器發出獲取請求,並運行python請求獲取我收到的預期結果,即id_rsa.pub文件的內容。但是當從Flask應用程序發出確切的請求時,它會給我一個錯誤。

ConnectionError: HTTPConnectionPool(host='127.0.1.1', port=9090): Max retries exceeded with url: /id_rsa.pub (Caused by <class 'socket.error'>: [Errno 111] Connection refused) 

我沒有研究這個錯誤,因爲它涉及到Python的請求,但沒能找到確鑿的解決方案。我知道事實的文件送達,因爲我可以從瀏覽器下載它,我就可以發出請求

x = requests.get("http://127.0.1.1:9090/id_rsa.pub") 

能夠得到文件的內容,但它不燒瓶應用中出於某種原因。

回答

0

在第二個腳本請求:

r = requests.get("http://127.0.0.1:5000/%s/%s"%(local_ip,port)) 

發生在服務器啓動監聽之前,在該腳本的底部。燒瓶應用同時發出一個即時請求回:

rmt_response = requests.get('http://127.0.1.1:9090/id_rsa.pub', timeout=1) 

如果服務器已經聽,只是緩慢,超時參數會的工作,但因爲服務器沒有聽,在「連接被拒絕」立即發生。 9090上的服務器甚至在監聽之前,您的燒錄請求會引發異常。

爲了完成這項工作,您必須在接收傳入請求和發出出站請求之間在燒瓶應用程序中引入延遲,否則在服務器開始偵聽之後將啓動請求設置爲在線程中運行。

相關問題