在远程服务器上运行本地 python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20499074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:37:26  来源:igfitidea点击:

Run local python script on remote server

pythonsshremote-debuggingscp

提问by qweruiop

I'm debugging some python script that must run on my virtual machine. And, I prefer to edit the scripts locally(outside of virtual machines). So I find it's tediousto scpmodified scripts to virtual machines every time. Can anyone suggests some effective way?

我正在调试一些必须在我的虚拟机上运行的 python 脚本。而且,我更喜欢在本地(虚拟机之外)编辑脚本。所以我觉得这是乏味scp每一次修改的脚本到虚拟机。任何人都可以提出一些有效的方法吗?

Particularly, I'm wondering if it's possible to execute python scripts on remote PVM. Something like that:

特别是,我想知道是否可以在远程 PVM 上执行 python 脚本。类似的东西:

python --remote [email protected] hello.py //**FAKED**, served to explain ONLY

采纳答案by asdfg

It is possible using ssh. Python accepts hyphen(-) as argument to execute the standard input,

可以使用 ssh。Python 接受连字符(-) 作为参数来执行标准输入,

cat hello.py | ssh [email protected] python -

Run python --helpfor more info.

运行python --help以获取更多信息。

回答by smeso

You can do it via ssh.

你可以通过 ssh 来完成。

ssh [email protected] "python ./hello.py"

ssh [email protected] "python ./hello.py"

You can also edit the script in ssh using a textual editor or X11 forwarding.

您还可以使用文本编辑器或 X11 转发在 ssh 中编辑脚本。

回答by Andreas N

Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach.

虽然这个问题不是很新,并且已经选择了答案,但我想分享另一种不错的方法。

Using the paramikolibrary - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script. So this solution is pretty much independent of an IDE.

使用paramiko库 - SSH2 的纯 Python 实现 - 您的 Python 脚本可以通过 SSH 连接到远程主机,将自身(!)复制到该主机,然后在远程主机上执行该副本。远程进程的标准输入、标准输出和标准错误将在您的本地运行脚本中可用。所以这个解决方案几乎独立于 IDE。

On my local machine, I run the script with a cmd-line parameter 'deploy', which triggers the remote execution. Without such a parameter, the actual code intended for the remote host is run.

在我的本地机器上,我使用 cmd 行参数“deploy”运行脚本,这会触发远程执行。如果没有这样的参数,将运行用于远程主机的实际代码。

import sys
import os

def main():
    print os.name

if __name__ == '__main__':
    try:
        if sys.argv[1] == 'deploy':
            import paramiko

            # Connect to remote host
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect('remote_hostname_or_IP', username='john', password='secret')

            # Setup sftp connection and transmit this script
            sftp = client.open_sftp()
            sftp.put(__file__, '/tmp/myscript.py')
            sftp.close()

            # Run the transmitted script remotely without args and show its output.
            # SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)
            stdout = client.exec_command('python /tmp/myscript.py')[1]
            for line in stdout:
                # Process each line in the remote output
                print line

            client.close()
            sys.exit(0)
    except IndexError:
        pass

    # No cmd-line args provided, run script normally
    main()

Exception handling is left out to simplify this example. In projects with multiple script files you will probably have to put all those files (and other dependencies) on the remote host.

为了简化这个例子,省略了异常处理。在具有多个脚本文件的项目中,您可能必须将所有这些文件(和其他依赖项)放在远程主机上。

回答by alisenby94

I've had to do this before using Paramiko in a case where I wanted to run a dynamic, local PyQt4 script on a host running an ssh server that has connected my OpenVPN server and ask for their routing preference (split tunneling).

如果我想在运行 ssh 服务器的主机上运行一个动态的本地 PyQt4 脚本,该主机连接了我的 OpenVPN 服务器并询问他们的路由首选项(拆分隧道),那么在使用 Paramiko 之前,我必须这样做。

So long as the ssh server you are connecting to has all of the required dependencies of your script (PyQt4 in my case), you can easily encapsulate the data by encoding it in base64 and use the exec()built-in function on the decoded message. If I remember correctly my one-liner for this was:

只要您连接的 ssh 服务器具有脚本的所有必需依赖项(在我的情况下为 PyQt4),您就可以通过将数据编码为 base64 来轻松封装数据,并exec()在解码的消息上使用内置函数。如果我没记错的话,我的单线是:

stdout = client.exec_command('python -c "exec(\"' + open('hello.py','r').read().encode('base64').strip('\n') + '\".decode(\"base64\"))"' )[1]

It is hard to read and you have to escape the escape sequences because they are interpreted twice (once by the sender and then again by the receiver). It also may need some debugging, I've packed up my server to PCS or I'd just reference my OpenVPN routing script.

它很难阅读,您必须转义转义序列,因为它们会被解释两次(一次由发送者解释,一次由接收者解释)。它也可能需要一些调试,我已经将我的服务器打包到 PCS 或者我只是引用我的 OpenVPN 路由脚本。

The difference in doing it this way as opposed to sending a file is that it never touches the disk on the server and is run straight from memory (unless of course they log the command). You'll find that encapsulating information this way (although inefficient) can help you package data into a single file.

以这种方式与发送文件不同的是,它永远不会接触服务器上的磁盘,而是直接从内存中运行(除非他们记录命令)。您会发现以这种方式封装信息(尽管效率低下)可以帮助您将数据打包到单个文件中。

For instance, you can use this method to include raw data from external dependencies (i.e. an image) in your main script.

例如,您可以使用此方法在主脚本中包含来自外部依赖项(即图像)的原始数据。

回答by neric

ssh user@machine python < script.py - arg1 arg2

Because cat |is usually not necessary

因为cat |通常没有必要