Nhome
Nhome

Reputation: 313

SCP in python by using password

I have been trying to do scp a file to a remote computer by using password. 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 in How to scp in python?, 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?

p.s. I have to use password not the key if your answer depends on that.

Upvotes: 9

Views: 27335

Answers (2)

Alex Taylor
Alex Taylor

Reputation: 8853

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

Upvotes: 9

Gajen Sunthara
Gajen Sunthara

Reputation: 4816

This is working as Jan 2019:

Install required Python packages:

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:

enter image description here

Upvotes: 1

Related Questions