【问题标题】:Remote control functions of a python script running on another computer在另一台计算机上运行的 python 脚本的远程控制功能
【发布时间】:2019-01-29 07:04:10
【问题描述】:

所以想象两台我都可以完全控制的计算机,我将它们称为计算机 A 和计算机 B。

在计算机A上,有一个python脚本在后台运行,具有多个功能,其中一个能够创建并显示一个消息框:(这只是一个示例)

def msg_box(text,title):
    MessageBox = ctypes.windll.user32.MessageBoxW
    MessageBox(None, text, title, 0)

我想要做的是从计算机 B 访问在计算机 A 上运行的脚本的功能,在 msg_box 函数的情况下,我希望能够在计算机 B 上使用我的任何参数调用它想要,它将在计算机 A 上执行。我是初学者,我不知道如何在计算机之间进行此链接,我提醒您,我对它们都有完全控制权,并且它们都连接到我的本地网络.有人建议我使用 ssh 服务器,有人能给我一些想法吗?

【问题讨论】:

  • 您可以使用socket 进行交流。
  • 你能给我一些关于如何在这个特定任务中使用套接字的提示吗?只是开始,我会去研究更多
  • 您可以查找类似如何使用 Python 制作简单的聊天服务器/客户端的内容。而不是聊天,您将只是发送命令。
  • 这是个好主意,谢谢,我会研究一下,看看我能做什么

标签: python


【解决方案1】:

这听起来像是Pyro4 package 的工作。这是一个基于他们的"Simple Example" 的示例,其中包含一些额外的代码来自动启动名称服务器并通过网络进行侦听。

首先在每台机器上使用这个命令安装Pyro4:

pip install pyro4

在服务器上,将此脚本保存为server.py,然后通过python server.py在终端窗口中运行它:

# saved as server.py
import Pyro4, Pyro4.naming
import socket, threading

# Define an object that will be accessible over the network.
# This is where all your code should go...
@Pyro4.expose
class MessageServer(object):
    def show_message(self, msg):
        print("Message received: {}".format(msg))


# Start a Pyro nameserver and daemon (server process) that are accessible
# over the network. This has security risks; see 
# https://pyro4.readthedocs.io/en/stable/security.html
hostname = socket.gethostname()
ns_thread = threading.Thread(
    target=Pyro4.naming.startNSloop, kwargs={'host': hostname}
)
ns_thread.daemon = True   # automatically exit when main program finishes
ns_thread.start()
main_daemon = Pyro4.Daemon(host=hostname)

# find the name server
ns = Pyro4.locateNS()
# register the message server as a Pyro object
main_daemon_uri = main_daemon.register(MessageServer)
# register a name for the object in the name server
ns.register("example.message", main_daemon_uri)

# start the event loop of the main_daemon to wait for calls
print("Message server ready.")
main_daemon.requestLoop()

在客户端,将其保存为client.py 并使用python client.py 运行它:

# saved as client.py
import Pyro4
import sys

print("What is your message?")
msg = sys.stdin.readline().strip()

# lookup object uri on name server and create a proxy for it
message_server = Pyro4.Proxy("PYRONAME:example.message")
# call method on remote object
message_server.show_message(msg)

请注意,将 Pyro 设置为通过您的网络进行监听存在安全风险。所以你应该在继续之前阅读他们的section on security。但这应该足以让您入门。

如果您想要一个只使用标准库的解决方案,您可以查看我在a different answer 中的基于套接字的客户端-服务器设置。或者您可以考虑在服务器上设置flask 网络服务器,然后在客户端使用urllib2 访问服务器并调用正确的操作(可能通过GETPOST 请求)。但这些都比这更困难。

另一种选择是使用不同的进程间通信包,例如 PyZMQ、redis、mpi4py 或 zmq_object_exchanger。请参阅this question 了解一些想法。

【讨论】:

  • 您正在链接到一个已弃用的位置,Pyro4 文档的正确新位置在这里:pyro4.readthedocs.io
  • 谢谢,已修复!
  • 几乎 :) “简单示例”和“安全章节”链接仍然指向旧网址。
猜你喜欢
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 2014-01-21
  • 2022-08-16
相关资源
最近更新 更多