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

2024-05-17 05:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

特别是,我想知道是否可以在远程PVM上执行python脚本。像这样的:

python --remote user@192.168.1.101 hello.py //**FAKED**, served to explain ONLY

Tags: to方法py脚本编辑onlyhello远程
3条回答

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

cat hello.py | ssh user@192.168.1.101 python -

有关详细信息,请运行python--help。

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

因为cat |通常不需要

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

使用paramiko库(SSH2的纯python实现),python脚本可以通过SSH连接到远程主机,复制自身(!)到该主机,然后在远程主机上执行该副本。远程进程的Stdin、stdout和stderr将在本地运行脚本中可用。所以这个解决方案与IDE几乎是独立的。

在本地计算机上,我使用命令行参数'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()

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

相关问题 更多 >