Programing

파이썬에서 scp하는 방법?

lottogame 2020. 6. 15. 08:18
반응형

파이썬에서 scp하는 방법?


파이썬에서 파일을 scp하는 가장 파이썬적인 방법은 무엇입니까? 내가 아는 유일한 길은

os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )

이것은 해킹이며 Linux와 같은 시스템 외부에서는 작동하지 않으며 이미 원격 호스트에 암호가없는 SSH를 설정하지 않은 경우 암호 프롬프트를 피하기 위해 Pexpect 모듈의 도움이 필요합니다.

Twisted 's를 알고 conch있지만 저수준 ssh 모듈을 통해 직접 scp를 구현하지 않는 것이 좋습니다.

paramikoSSH와 SFTP를 지원하는 Python 모듈을 알고 있습니다 . 그러나 SCP를 지원하지 않습니다.

배경 : SFTP는 지원하지 않지만 SSH / SCP는 지원하는 라우터에 연결하고 있으므로 SFTP는 옵션이 아닙니다.

편집 : 이것은 SCP 또는 SSH를 사용하여 Python에서 원격 서버로 파일을 복사하는 방법 의 복제본 입니까? . 그러나 그 질문은 파이썬 내에서 키를 다루는 scp 특정 답변을 제공하지 않습니다. 비슷한 코드를 실행하는 방법을 기대하고 있습니다.

import scp

client = scp.Client(host=host, user=user, keyfile=keyfile)
# or
client = scp.Client(host=host, user=user)
client.use_system_keys()
# or
client = scp.Client(host=host, user=user, password=password)

# and then
client.transfer('/etc/local/filename', '/etc/remote/filename')

Paramiko 용 Python scp 모듈을 사용해보십시오 . 사용하기 매우 쉽습니다. 다음 예를 참조하십시오.

import paramiko
from scp import SCPClient

def createSSHClient(server, port, user, password):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(server, port, user, password)
    return client

ssh = createSSHClient(server, port, user, password)
scp = SCPClient(ssh.get_transport())

그런 다음 전화 scp.get()하거나 scp.put()SCP 작업을 수행하십시오.

( SCPClient 코드 )


Pexpect ( 소스 코드 ) 시도에 관심이있을 수 있습니다 . 이렇게하면 암호에 대한 대화식 프롬프트를 처리 할 수 ​​있습니다.

다음은 기본 웹 사이트의 사용법 예제 (ftp의 경우)입니다.

# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')

You could also check out paramiko. There's no scp module (yet), but it fully supports sftp.

[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.

scp.py for paramiko


if you install putty on win32 you get an pscp (putty scp).

so you can use the os.system hack on win32 too.

(and you can use the putty-agent for key-managment)


sorry it is only a hack (but you can wrap it in a python class)


Couldn't find a straight answer, and this "scp.Client" module doesn't exist. Instead, this suits me:

from paramiko import SSHClient
from scp import SCPClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')

with SCPClient(ssh.get_transport()) as scp:
   scp.put('test.txt', 'test2.txt')
   scp.get('test2.txt')

Have a look at fabric.transfer.

from fabric import Connection

with Connection(host="hostname", 
                user="admin", 
                connect_kwargs={"key_filename": "/home/myuser/.ssh/private.key"}
               ) as c:
    c.get('/foo/bar/file.txt', '/tmp/')

You can use the package subprocess and the command call to use the scp command from the shell.

from subprocess import call

cmd = "scp user1@host1:files user2@host2:files"
call(cmd.split(" "))

As of today, the best solution is probably AsyncSSH

https://asyncssh.readthedocs.io/en/latest/#scp-client

async with asyncssh.connect('host.tld') as conn:
    await asyncssh.scp((conn, 'example.txt'), '.', recurse=True)

It has been quite a while since this question was asked, and in the meantime, another library that can handle this has cropped up: You can use the copy function included in the Plumbum library:

import plumbum
r = plumbum.machines.SshMachine("example.net")
   # this will use your ssh config as `ssh` from shell
   # depending on your config, you might also need additional
   # params, eg: `user="username", keyfile=".ssh/some_key"`
fro = plumbum.local.path("some_file")
to = r.path("/path/to/destination/")
plumbum.path.utils.copy(fro, to)

Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.


I while ago I put together a python SCP copy script that depends on paramiko. It includes code to handle connections with a private key or SSH key agent with a fallback to password authentication.

http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/


If you are on *nix you can use sshpass

sshpass -p password scp -o User=username -o StrictHostKeyChecking=no src dst:/path

I don't think there's any one module that you can easily download to implement scp, however you might find this helpful: http://www.ibm.com/developerworks/linux/library/l-twist4.html

참고URL : https://stackoverflow.com/questions/250283/how-to-scp-in-python

반응형