如何使用 SCP 或 SSH 将文件复制到 Python 中的远程服务器? [英] How to copy a file to a remote server in Python using SCP or SSH?

查看:28
本文介绍了如何使用 SCP 或 SSH 将文件复制到 Python 中的远程服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的本​​地机器上有一个文本文件,它是由在 cron 中运行的每日 Python 脚本生成的.

I have a text file on my local machine that is generated by a daily Python script run in cron.

我想添加一些代码,以便通过 SSH 将该文件安全地发送到我的服务器.

I would like to add a bit of code to have that file sent securely to my server over SSH.

推荐答案

您可以调用scp bash 命令(它通过 SSH 复制文件)和 subprocess.run:

You can call the scp bash command (it copies files over SSH) with subprocess.run:

import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "joe@srvr.net:/path/to/foo.bar"])

如果您要在同一个 Python 程序中创建要发送的文件,您需要在 with 块之外调用 subprocess.run 命令' 用于打开文件(或者如果您没有使用 with 块,则首先在文件上调用 .close() ),这样您就知道它已刷新到磁盘来自 Python.

If you're creating the file that you want to send in the same Python program, you'll want to call subprocess.run command outside the with block you're using to open the file (or call .close() on the file first if you're not using a with block), so you know it's flushed to disk from Python.

您需要事先生成(在源机器上)并安装(在目标机器上)一个 ssh 密钥,以便 scp 自动使用您的公共 ssh 密钥进行身份验证(换句话说,因此您的脚本不会要求密码).

You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).

这篇关于如何使用 SCP 或 SSH 将文件复制到 Python 中的远程服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆