기계는 거짓말하지 않는다

Python SSH Client 원격 연결 (Paramiko) 본문

Python

Python SSH Client 원격 연결 (Paramiko)

KillinTime 2023. 2. 24. 20:29

Python에서 Paramiko를 이용한 간략한 SSH Client 원격 연결 방법이다.

설치

pip install paramiko

사용

Paramiko Docs

 

Client — Paramiko documentation

Client SSH client & key policies class paramiko.client.SSHClient A high-level representation of a session with an SSH server. This class wraps Transport, Channel, and SFTPClient to take care of most aspects of authenticating and opening channels. A typical

docs.paramiko.org

import paramiko
import time

cli = paramiko.SSHClient()
# set_missing_host_key_policy: 알려진 호스트 키 없이 서버에 연결할 때 사용할 정책 설정
# AutoAddPolicy: 알려지지 않은 서버에 연결할 때 키를 추가하고 저장
cli.set_missing_host_key_policy(paramiko.AutoAddPolicy)
# hostname에는 domain 주소 또는 IP 주소를 입력한다.
cli.connect("hostname", port=22, username="username", password="password")

timeout = 3
stdin, stdout, stderr = cli.exec_command("ls -al")

endtime = time.time() + timeout

# timeout 시간동안 응답이 없을 경우
while not stdout.channel.eof_received:
    time.sleep(1)
    if time.time() > endtime:
        stdout.channel.close()
        break

lines = stdout.readlines()
print(''.join(lines))

cli.close()
Comments