urllib.error.URLError:<urlopen错误[Errno 113]主机无路由>

我正在尝试创建一个主代理脚本,其中主服务器从代理获取信息。信息,例如:

  • 主机名用法
  • CPU使用率
  • 磁盘使用情况
  • 内存使用量

我已将其放入返回数据的函数中。即将发送数据时,出现错误:

Traceback (most recent call last):
  File "./agent.py",line 42,in <module>
    send_data(out_data)
  File "./agent.py",line 36,in send_data
    with urllib.request.urlopen(req) as response :
  File "/usr/lib64/python3.6/urllib/request.py",line 223,in urlopen
    return opener.open(url,data,timeout)
  File "/usr/lib64/python3.6/urllib/request.py",line 526,in open
    response = self._open(req,data)
  File "/usr/lib64/python3.6/urllib/request.py",line 544,in _open
    '_open',req)
  File "/usr/lib64/python3.6/urllib/request.py",line 504,in _call_chain
    result = func(*args)
  File "/usr/lib64/python3.6/urllib/request.py",line 1346,in http_open
    return self.do_open(http.client.HTTPConnection,line 1320,in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 113] No route to host>

我检查了两个VM之间是否存在连接。一个人的IP地址= 192.168.234.2(主服务器),其他人192.168.234.10(代理人)。代理的路由表显示routing table agent,这是两个ping

之间的ping

Agent.py

#!/bin/python3
##importeer onderstaande modules om deze te gebruiken##
import psutil
import socket
import time
import urllib.parse
import urllib.request

url = 'http://192.168.234.2/cgi-bin/master.py'
##de output van bovenstaande prints word geplaats in deze variabel om deze in onderstaande variabelen door te sturen##


#De dictionairys worden klaar gezet om gebruikt te worden
def save_data():
    return {
        'machine'   : socket.gethostname(),'memory'    : psutil.virtual_memory()[2],'disk'      : psutil.disk_usage('/').percent,'cpu'       : psutil.cpu_percent()
    }

#De data wordt in de dictionairys gezet
def print_info(out_data):
    print ("Het script heeft gedraaid op: ",time.strftime('%m/%d/%Y %H:%M:%S'))
    print ('De naam van deze host machine is:',out_data['machine'])
    print ('Het geheugen is ',out_data['memory'],'% in gebruik')
    print ('De schijf is ',out_data['disk'],'% vol')
    print ('Het CPU percentage dat in gebruik is: ',out_data['cpu'])

#de data wordt naar de master verzonden
def send_data(out_data):
    data = urllib.parse.urlencode(out_data)
    data = data.encode('ascii')
    req = urllib.request.Request(url,data)
    with urllib.request.urlopen(req) as response :
        the_page = response.read()


out_data = save_data()        
print_info(out_data)
send_data(out_data)

Master.py

#!/usr/bin/python3
###importeren van modules om deze vervolgens te kunnen gebruiken in het script###
import cgi,cgitb
import matplotlib.pyplot as plt
import io
import sqlite3

#maak een instance van een field storage
cgitb.enable()
form = cgi.FieldStorage()

#het verkrijgen van data van de velden die vanuit de agent worden opgestuurd.
def get_data():
    system_data = {
    "machine" : form.getvalue('machine'),"cpu": form.getvalue('cpu'),"mem": form.getvalue('mem'),"disk": form.getvalue('disk')}
    return system_data

#print ("Content-type:text/html\n\n")

current_data = get_data()

con = sqlite3.connect('toets_school.db')
cursor = con.cursor()
cursor.execute("CREATE TABLE if NOT EXISTS gegevens ('machine',VARCHAR,'cpu' float,'mem' float,'disk' float)")
cursor.execute("INSERT INTO gegevens (machine,cpu,mem,disk) VALUES ('"+str(current_data["machine"])+"','"+str(current_data["cpu"])+"','"+str(current_data["mem"])+"','"+str(current_data["disk"])+"')")
cursor.execute("SELECT cpu,disk FROM gegevens WHERE machine = '"+str(current_data["machine"]+"'")
data = cursor.fetchall()

cpulijst = []
memlijst = []
disklijst = []

for info in data:
    cpulijst.append(info[0])
    memlijst.append(info[1])
    disklijst.append(info[2])

#print(data)
con.commit()
get_data()

print (cpulijst)
def chart_cpu():
    plt.plot(cpulijst)
    plt.title("CPU gebruik")
    plt.xlabel('minuten')
    plt.ylabel('percentage(%)')
    plt.grid(True)
    plt.savefig("cpu.png")
    plt.show()

def chart_memory():
    plt.plot(memlijst)
    plt.title("Geheugen")
    plt.xlabel('minuten')
    plt.ylabel('percentage (%)')
    plt.grid(True)
    plt.savefig("memory.png")
    plt.show()

def chart_disk_usage():
    plt.plot(disklijst)
    plt.title("Schuifruimte")
    plt.xlabel('minuten')
    plt.ylabel('(%)in gebruik')
    plt.grid(True)
    plt.savefig("disk_usage.png")
    plt.show()

chart_cpu()
chart_disk_usage()
chart_memory()

print ("Content-type:text/html\n\n")
print ("<center>")
print ('De naam van deze machine is :',machine)
print ("<br>")
print ("<html><head><title>Website HAF sportschool</title></head><body>")
print("<img src='data:image/png;base64,"+str(base64.b64encode(buf.getvalue()).decode('ascii'))+"' />")
print("<img src='data:image/png;base64,"+str(base64.b64encode(buf2.getvalue()).decode('ascii'))+"' />")
print ("</body></html>")


conn.close()

我希望代理将发送的信息存储在函数save_data中,并传递给out_data。并且数据将通过函数def send_data发送到主服务器。

编辑:在比尔·洪内克(Bill Huneke)​​的表扬之后,非常感谢。第一个问题已解决。使用Linux命令:

sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --reload

我能够卷曲master.py。现在我的问题是,主服务器上的数据库仅被填充为“无”。

有人知道如何解决这个问题吗?

michaelkid 回答:urllib.error.URLError:<urlopen错误[Errno 113]主机无路由>

您可能想通过尝试首先从Python外部获取该URL来解决此问题。

因此,运行“ curl http://192.168.234.2/cgi-bin/master.py”,看看会得到什么。您可能在.2处配置了错误的Web服务器,或者有防火墙规则或其他阻止与Web服务器通信的规则。

编辑:澄清-“没有路由到主机”错误不一定表示路由是问题。误导,我知道。它还可能表明特定端口(在本例中为http,80)不可访问/未响应。 Ping是一个很好的步骤,但不能完全诊断出这一点。

更新(以下问题更改后):

很高兴听到您解决了您最初询问的“主机没有路由”错误。

我了解您现在正在发现更多问题。阅读完脚本的其余部分,我会说您有许多不寻常的元素,在我看来它们并不起作用。我建议您逐步构建系统。从脚本中删除所有内容,然后放一件事,使其完美运行。从那里进行迭代:将您的工作置于源代码管理(例如Git)中,以便您可以在进行过程中重新使用它。继续添加功能,向数据库添加更多字段,等等。慢慢来,逐步构建。随便问一些个人问题。

首先处理只有一个值和一个字段的非常基础的数据库插入。如果事情不正常,请使用其他工具(如curl一样)来确认交互组件确实在说您认为他们在说的话。例如,您应该查看发送到服务器的内容,以确认发送的Form数据确实格式正确,并且正是您的主数据库试图解析的内容。

此外,您要构建的系统非常适合Django或Flask之类的框架。将您的项目放在其中之一中将提供引导(最终)成功的指南。

祝你好运

本文链接:https://www.f2er.com/3151294.html

大家都在问