qwe*_*iop 31 python ssh scp remote-debugging
我正在调试一些必须在我的虚拟机上运行的python脚本.而且,我更喜欢在本地编辑脚本(在虚拟机之外).所以我发现每次都要将脚本修改为虚拟机是很繁琐的scp.有人能建议一些有效的方法吗?
特别是,我想知道是否可以在远程PVM上执行python脚本.像这样的东西:
python --remote user@192.168.1.101 hello.py //**FAKED**, served to explain ONLY
Run Code Online (Sandbox Code Playgroud)
asd*_*dfg 54
可以使用ssh.Python接受连字符( - )作为参数来执行标准输入,
cat hello.py | ssh user@192.168.1.101 python -
Run Code Online (Sandbox Code Playgroud)
运行python --help以获取更多信息.
And*_*s N 38
虽然这个问题不是很新,而且已经选择了答案,但我想分享另一个好方法.
使用paramiko库 - SSH2的纯python实现 - 您的python脚本可以通过SSH连接到远程主机,将自身(!)复制到该主机,然后在远程主机上执行该副本.远程进程的Stdin,stdout和stderr将在您的本地运行脚本上提供.所以这个解决方案几乎独立于IDE.
在我的本地计算机上,我使用cmd-line参数'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()
Run Code Online (Sandbox Code Playgroud)
省略了异常处理以简化此示例.在具有多个脚本文件的项目中,您可能必须将所有这些文件(和其他依赖项)放在远程主机上.
ner*_*ric 15
ssh user@machine python < script.py - arg1 arg2
Run Code Online (Sandbox Code Playgroud)
因为cat |通常没有必要
您可以通过ssh完成。
ssh user@192.168.1.101 "python ./hello.py"
您还可以使用文本编辑器或X11转发在ssh中编辑脚本。