파이썬에서 scp 하는 법?
파이썬에서 파일을 스크핑하는 가장 피톤적인 방법은 무엇인가?내가 아는 유일한 길은
os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )
이는 해킹이며, Linux와 유사한 시스템 외부에서는 작동하지 않으며, 원격 호스트에 암호 없는 SSH를 이미 설정하지 않은 경우 암호 프롬프트를 피하기 위해 Pexpect 모듈의 도움이 필요하다.나는 트위스트의 존재를 알고 있다.
conch
하지만 저수준의 ssh 모듈을 통해 직접 scp를 구현하는 것은 피하고 싶다.알고 있다
paramiko
SSH 및 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 작업을 한다.(SCPCLent 코드)당신은 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')
정답을 못 찾았고, 이 "scp"도 못 찾았어.클라이언트" 모듈이 존재하지 않음대신, 이것은 나에게 잘 어울린다:
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')
파라미코도 확인해 볼 수 있어.scp 모듈(yet)은 없지만 sftp를 완벽하게 지원한다.[EDIT] 미안, 파라미코를 언급했던 선을 놓쳤다.다음의 모듈은 파라미코에 대한 scp 프로토콜의 구현에 불과하다.paramiko나 conch(python에 대해 내가 알고 있는 유일한 ssh 구현)를 사용하지 않으려면 파이프를 사용하여 정기적인 ssh 세션을 실행하기 위해 이 작업을 다시 수행할 수 있다.
putty를 win32에 설치하면 pscp(putty scp)를 받는다.win32에서도 os.system 해킹을 사용할 수 있도록.(키 분할에 putty-agent를 사용할 수 있음)
미안하지만 그것은 해킹일 뿐이다(하지만 당신은 그것을 파이톤 클래스로 포장할 수 있다)오늘부로 가장 좋은 해결책은 아마도
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)
패키지 하위 프로세스와 명령 호출을 사용하여 셸에서 scp 명령을 사용할 수 있다.
from subprocess import call cmd = "scp user1@host1:files user2@host2:files" call(cmd.split(" "))
직물.전송을 보십시오.
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/')
import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect('<IP Address>', username='<User Name>',password='' ,key_filename='<.PEM File path') #Setup sftp connection and transmit this script print ("copying") sftp = client.open_sftp() sftp.put(<Source>, <Destination>) sftp.close()
이 질문을 받은 지 꽤 오래되었고, 그 사이에 이것을 다룰 수 있는 또 다른 도서관이 잘려나갔다: 플럼붐 도서관에 포함된 복사 기능을 사용할 수 있다:
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)
*nix에 있는 경우 sshpass를 사용할 수 있음
sshpass -p password scp -o User=username -o StrictHostKeyChecking=no src dst:/path
흠, 아마도 다른 옵션은 sshfs 같은 것을 사용하는 것일 것이다.라우터가 마운트되면 파일을 완전히 복사할 수 있다.그것이 당신의 특정 용도에 적합한지는 잘 모르겠지만, 그것은 유용하게 사용할 수 있는 좋은 해결책이다.나는 얼마 전에 paramiko에 의존하는 python SCP 카피 스크립트를 작성했다.개인 키나 SSH 키 에이전트와의 연결을 암호 인증으로 대체하는 코드를 포함한다.
http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/
참조URL: https://stackoverflow.com/questions/250283/how-to-scp-in-python
'IT이야기' 카테고리의 다른 글
TypeError: 해시가 불가능한 유형: 'dict' (0) | 2022.03.08 |
---|---|
vue-cli 프로젝트에서 포트 번호를 변경하는 방법 (0) | 2022.03.08 |
Vue-cli 버전 3 베타 웹 팩 구성 (0) | 2022.03.08 |
행 삭제 후 Boostrap-Vue 테이블 새로 고침 (0) | 2022.03.08 |
기본 키 반응 - 플랫리스트와 함께 키 추출기 사용 (0) | 2022.03.08 |