Python paramiko 모듈 의 설치 및 사용

1949 단어 paramikoPython
paramiko 는 Python 언어 로 SSH 2 프로 토 콜 에 따라 암호 화 와 인증 방식 을 지원 하고 원 격 서버 에 연결 하여 명령 을 수행 하거나 다운로드 파일 을 업로드 합 니 다.
1.paramiko 설치
pip3 install paramiko

2.사용자 이름 암호 방식 으로 원 격 으로 명령 을 수행 합 니 다.
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  #          host key
ssh.connect('127.0.0.1', 22, 'username', 'password')  #     IP、  、   、  
stdin, stdout, stderr = ssh.exec_command('df -h')  #            
for line in stdout:
	print(line)
ssh.close()  #   ssh  

3.사용자 이름 비밀번호 로 파일 업로드 또는 다운로드
import paramiko
t = paramiko.Transport('127.0.0.1', 22)
t.connect(username='username', password='password')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('local_file', 'remote_folder')
t.close()
import paramiko
t = paramiko.Transport('127.0.0.1', 22)
t.connect(username='username', password='password')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('remote_file', 'local_folder')
t.close()

4.ssh key 방식 으로 원 격 으로 명령 을 실행 합 니 다.(원 격 호스트 가 공개 키 를 받 아 들 였 을 때)
import paramiko

private_key_path = '/home/xxx/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(private_key_path)

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', 22, username='username', pkey=key)
stdin, stdout, stderr = ssh.exec_command('df')
print(stdout.read())
ssh.close()

5.scp 방식 으로 원 격 으로 명령 을 수행 합 니 다.
import paramiko

scp = paramiko.Transport(('127.0.0.1', 22))
scp.connect(username='username', password='password')
channel = scp.open_session()
channel.exec_command('touch hello/test.txt')
channel.close()
scp.close()

좋은 웹페이지 즐겨찾기