[python] 파이썬에서 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')


답변

당신은 또한 paramiko를 확인할 수 있습니다 . scp 모듈 (아직)은 없지만 sftp를 완전히 지원합니다.

[편집] 죄송합니다. paramiko를 언급 한 줄을 놓쳤습니다. 다음 모듈은 단순히 paramiko에 대한 scp 프로토콜의 구현입니다. paramiko 또는 conch (파이썬에 대해 알고있는 유일한 ssh 구현)를 사용하지 않으려면 파이프를 사용하여 일반 ssh 세션을 실행하도록이를 재 작업 할 수 있습니다.

paramiko의 scp.py


답변

정답을 찾지 못했습니다.이 “scp.Client”모듈이 없습니다. 대신, 이것은 나에게 적합합니다.

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


답변

win32에 putty를 설치하면 pscp (putty scp)가 표시됩니다.

win32에서도 os.system hack을 사용할 수 있습니다.

(그리고 키 관리에 퍼티 에이전트를 사용할 수 있습니다)


미안하지만 그것은 해킹 일뿐입니다 (그러나 파이썬 클래스로 포장 할 수는 있습니다)


답변

패키지 서브 프로세스 및 명령 호출을 사용하여 쉘에서 scp 명령을 사용할 수 있습니다.

from subprocess import call

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


답변

오늘날 가장 좋은 해결책은 아마도 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)