【问题标题】:How to send a function over sockets python如何通过套接字python发送函数
【发布时间】:2021-02-03 18:14:14
【问题描述】:

所以我正在学习套接字,特别是客户端服务器网络,我有一个问题是可以通过套接字发送函数吗?

我知道你可以这样做:

#class containing function, called printing_class
print.py
class printing_class(self):

def print(self):
    print("hello world")
#server.py
from print import printing_class

print = printing_class(self)
server.send(print) #pseudocode for send statement, sending print object

#client.py
print = client.receive() #pseudo code for print and receive
print.print() # by doing this, prints out hello world

通过发送一个对象,我可以访问它的方法然后打印它。

但是,我想知道有没有办法这样做:

#server.py
server.send(print("hello world"))

#client.py
client.receive() # when receiving from server, automatically prints it

是否可以通过套接字发送打印函数,当客户端收到它时,它会自动打印它?

【问题讨论】:

  • 一切都是可能的。没有简单的方法可以做到这一点,也不应该这样做。但这是可能的,并且允许它的服务器存在严重的安全漏洞,应该被黑客破坏;)
  • 哦,当你这么说的时候,我现在明白它的含义了,谢谢你的解释!
  • FluidLight 在回答中证明我错了。这实际上很容易做到。至于安全性,您可以(并且应该)添加一个安全层,防止任何人访问服务器......

标签: python sockets client-server


【解决方案1】:

可以使用名为RPyC 的库来实现。

  1. 为简单的服务器运行包含的 rpyc_classic.py 脚本(仅用于测试)。
  2. 使用客户端连接到它并发送您想要执行的 python 代码。

示例:

import rpyc
c = rpyc.classic.connect("localhost") # connect
c.execute("print('hi there')")   # print "hi there" on the host

rpyc 的众多功能之一是您可以限制要执行的函数(或者您可以自己定义)以不引起安全漏洞。

【讨论】:

  • 谢谢!这是唯一的方法吗,还是没有图书馆也可以?
  • 一个更简单的方法是将你的 python 代码发送到服务器并使用 exec/eval 来执行它。但由于涉及明显的安全风险,我强烈不推荐。
猜你喜欢
  • 1970-01-01
  • 2021-09-13
  • 2014-08-16
  • 1970-01-01
  • 2014-09-01
  • 2016-11-19
  • 1970-01-01
  • 2022-01-15
  • 2015-08-28
相关资源
最近更新 更多