You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RPyC C2服务器无法向客户端传输方法/库,报AttributeError错误求助

RPyC C2服务器无法暴露自定义方法,抛出AttributeError

错误信息

AttributeError: 'SlaveService' object has no attribute exposed_add

问题代码分析

服务器代码存在多个关键错误:

  1. 混入客户端连接代码:conn = rpyc.classic.connect("localhost", 18812)是客户端用来连接服务器的逻辑,放在服务器代码里会导致启动时错误尝试连接自身,直接删除即可。
  2. 类定义位置错误:MyService被嵌套在while True循环内,完全无必要,重复定义类会引发逻辑问题,需将类定义移至全局作用域。
  3. 类名拼写错误:启动服务器时写的Myservice应为MyService(Python大小写敏感),此错误导致服务器找不到自定义服务类,只能使用默认的SlaveService,自然不存在exposed_add方法。
  4. 方法内部错误:exposed_add里的变量名resukt是拼写错误,应改为result;且原方法无返回值,客户端调用后会得到None,需添加return result。

客户端代码问题:

调用远程方法时无需加exposed_前缀,RPyC会自动识别以exposed_开头的方法,直接调用conn.root.add(5, 6)即可。

修正后的代码

服务器代码

import rpyc
from rpyc.utils.server import ThreadedServer

class MyService(rpyc.Service):
    def on_connect(self, conn):
        print("connection made")
    def on_disconnect(self, conn):
        print("connection closed")
    def exposed_add(self, x, y):
        result = x + y
        print(result)
        print("jesus")
        return result  # 添加返回值给客户端

if __name__ == "__main__":
    server = ThreadedServer(MyService, port=18812, protocol_config={"allow_public_attrs": True})
    server.start()

客户端代码

import rpyc

conn = rpyc.connect("localhost", 18812)
rez = conn.root.add(5, 6)  # 无需加exposed_前缀
print(rez)

关于传输库的问题

如果要让客户端使用服务器端的库,可以在自定义服务中暴露获取模块的方法,示例如下:

# 服务器端新增方法
def exposed_get_module(self, module_name):
    import importlib
    return importlib.import_module(module_name)

客户端调用后即可使用服务器的模块:

# 客户端代码
math_module = conn.root.get_module("math")
print(math_module.sqrt(16))

注意:开放模块导入存在安全风险,仅在可控环境中使用。

内容的提问来源于stack exchange,提问作者erik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 02:48:16