[Python] Python SSH Paramiko

2022. 4. 12. 23:58

Paramiko

Welcome to Paramiko!

Paramiko는 클라이언트와 서버 기능을 모두 제공하는 SSH 프로토콜의 순수 Python 구현체(C와 Rust 확장을 사용하지만 암호화를 위해 사용)
일반적으로 원격 쉘 명령 실행과 파일전송과 같은 일반적인 클라이언트에 사용
Python 2.7 이상, 3.4 이상 사용할 수 있음

설치

python -m pip install paramiko

사용

연결

import paramiko

client = paramiko.SSHClient()
username = 'username'
password = 'password'

user_info_dict = {
    'username' : username,
    'password' : password,
}

client.connect('127.0.0.1', **user_info_dict)

~~~

client.close()

Host Key

ssh 접근 시 서버 컴퓨터가 내가 알던 컴퓨터가 맞는 지 확인하는 과정에 필요한 SSH Host Key를 저장한다.

ssh를 사용해봤다면 한번 쯤 공백 엔터, 'y', 'yes'를 입력했던 경험이 있을 것이다.

paramiko에선

SSHClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())

를 사용하여 Host key를 저장하게 할 수 있다.(기본값은 RejectPolicy)

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
server_info_dict = {
    'username' : username, # ID (str)
    'password' : password, # PW (str)
    'port'       : port,     # PORT (int)
    'hostname' : hostname  # IP (str)
}

client.connect(**server_info_dict)

함수

exec_command(명령) : 서버에서 명령을 실행, 명령 실행이 완료되면 채널이 닫히고 재사용할 수 없음


~

stdin, stdout, stderr =  client.exec_command(command) 
data = stdout.readlines()

exec_command로 sudo 사용


~

stdin, stdout, stderr =  client.exec_command(command)  # sudo 가 포함된 명령어
stdin.write(f'{password}\n')
stdin.flush() # write 후 flush를 해야 동작함

data = stdout.read()

하지만 내가 사용하던 경우 sudo 명령어로 실행시킬 수 없는 상황이였기에 invoke_shell을 사용하여
sudo su - 로 유저 변경 후 명령어를 실행시켰다.


def wait_stream(chan):
    time.sleep(1)
    out = err = ''

    while chan.recv_ready():
        out += chan.recv(1024)
        while chan.recv_stderr_ready():
            err += chan.recv_stderr(1024)

    return out, err

~

channel =  client.invoke_shell()
channel.send('sudo su -\n')
out, err = wait_stream(channel)

channel.send(f'{password}\n')
out, err = wait_stream(channel)

channel.send(f'{command}')
out, err = wait_stream(channel)


data = out.splitlines()

참고자료

Welcome to Paramiko!
Python Paramiko
lahuman.github.io

BELATED ARTICLES

more