使用密码在Python中实现SCP

8

我一直在尝试使用密码将文件通过scp传输到远程计算机。我使用了以下代码:

import os
import scp
client = scp.Client(host="104.198.152.xxx", username="nxxx", password="xxxxxx")
client.transfer("script.py", "~/script.py")

正如在 How to scp in python?中所建议的,但它会输出:
File "script.py", line 5, in <module>
    client = scp.Client(host="104.198.152.153", username="nazarihome", password="mohMOH13579")
AttributeError: 'module' object has no attribute 'Client'

我也尝试了其他人建议的方法,似乎它们都不起作用。有人有真正有效的建议吗?
附言:如果你的答案依赖于密码而不是密钥,那么我必须使用密码。

你试过使用 scp.SCPClient 而不是 scp.Client 吗? - silel
1
你复制了一个问题的示例,而不是答案。请再看一下你基于的帖子。 - Robert Seaman
你所提到的帖子中的代码并不是真实存在的,那只是一种心愿清单。 - Shiping
2个回答

9

scp.py GitHub页面提供了以下示例,使用paramiko库处理SSL:

from paramiko import SSHClient
from scp import SCPClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname='ip', 
            port = 'port',
            username='username',
            password='password',
            pkey='load_key_if_relevant')


# SCPCLient takes a paramiko transport as its only argument
scp = SCPClient(ssh.get_transport())

scp.put('file_path_on_local_machine', 'file_path_on_remote_machine')
scp.get('file_path_on_remote_machine', 'file_path_on_local_machine')

scp.close()

所以你需要的实际类型是 scp.SCPClient

1

这是截至2019年1月的工作状态:

安装所需的Python软件包:

pip install scp
pip install paramiko

在代码中包含库:

from paramiko import SSHClient
from scp import SCPClient

编写了一个函数:
# SSH/SCP Directory Recursively     
def ssh_scp_files(ssh_host, ssh_user, ssh_password, ssh_port, source_volume, destination_volume):
    logging.info("In ssh_scp_files()method, to copy the files to the server")
    ssh = SSHClient()
    ssh.load_system_host_keys()
    ssh.connect(ssh_host, username=ssh_user, password=ssh_password, look_for_keys=False)

    with SCPClient(ssh.get_transport()) as scp:
        scp.put(source_volume, recursive=True, remote_path=destination_volume)

现在你可以在代码的任何地方调用它:

ssh_scp_files(ssh_host, ssh_user, ssh_password, ssh_port, source_volume, destination_volume)

如果以上所有步骤都正确实现,你将在控制台/日志中看到成功的消息,如下所示:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接