如何使用SCP或SSH将文件复制到Python中的远程服务器? [英] How to copy a file to a remote server in Python using SCP or SSH?
问题描述
我的本地计算机上有一个文本文件,该文件由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命令(它通过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
块,请先在文件上输入),这样就知道它是从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屋!