简体   繁体   English

使用密码在python中的SCP

[英]SCP in python by using password

I have been trying to do scp a file to a remote computer by using password.我一直在尝试使用密码将文件 scp 发送到远程计算机。 I used this code:我使用了这个代码:

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

as it's suggested inHow to scp in python?正如如何在 python 中 scp 中所建议的那样 , but it outputs: ,但它输出:

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'

I also tried other ways that people suggest and seems that none of them works.我还尝试了人们建议的其他方法,但似乎它们都不起作用。 Does anybody have a suggestion that really works?有人有真正有效的建议吗?

ps I have to use password not the key if your answer depends on that. ps 如果您的答案取决于密码,我必须使用密码而不是密钥。

The scp.py GitHub page has the following example that uses itself with the paramiko library for handling SSL: 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()

So the actual type you want it is scp.SCPClient .所以你想要的实际类型是scp.SCPClient

This is working as Jan 2019:这是 2019 年 1 月:

Install required Python packages:安装所需的 Python 包:

pip install scp
pip install paramiko

Include library in the code:在代码中包含库:

from paramiko import SSHClient
from scp import SCPClient

Wrote a function for it:为它写了一个函数:

# 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)

Now call it anywhere you want in the code:现在在代码中你想要的任何地方调用它:

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

If all above implemented correctly, you will see the the successful messages in the console/logs like this:如果以上所有实现正确,您将在控制台/日志中看到成功的消息,如下所示:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM