파이썬으로 ssh 프로토콜을 사용할 수 있는 paramiko 라이브러리에 대한 간단한 사용 예제
크게 단일 명령을 전송하는 예제와,
당연히 설치는 pip로 가능하다.
pip install paramiko
pip3 install paramiko
자세한 설명은 아래 Docs에 나와있다.
Welcome to Paramiko’s documentation! — Paramiko documentation
Welcome to Paramiko’s documentation! This site covers Paramiko’s usage & API documentation. For basic info on what Paramiko is, including its public changelog & how the project is maintained, please see the main project website. API documentation The h
docs.paramiko.org
ssh 명령 전송
ssh서버로 명령을 전송하고, 그 결과를 확인한다.
import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('hostname', username='username', password='password')
stdin, stdout, stderr = client.exec_command('ls -al')
print(stdout.read().decode())
client.close()
Output
total 40
-rw-r--r-- 1 jhkim jhkim 58 Aug 23 10:51 a.py
drwxr-xr-x 2 jhkim jhkim 4096 Apr 4 20:57 Bookshelf
drwxr-xr-x 2 jhkim jhkim 4096 Aug 22 17:58 Desktop
drwxr-xr-x 2 jhkim jhkim 4096 Apr 4 21:18 Documents
drwxr-xr-x 2 jhkim jhkim 4096 Apr 4 21:18 Downloads
drwxr-xr-x 2 jhkim jhkim 4096 Apr 4 21:18 Music
drwxr-xr-x 2 jhkim jhkim 4096 Apr 4 21:18 Pictures
drwxr-xr-x 2 jhkim jhkim 4096 Apr 4 21:18 Public
drwxr-xr-x 2 jhkim jhkim 4096 Apr 4 21:18 Templates
drwxr-xr-x 2 jhkim jhkim 4096 Apr 4 21:18 Videos
간단하게 ssh 호스트에 접속하여, ls- al명령을 실행하는 코드다.
paramiko.SSHClient()
SSHClient 객체를 생성합니다.
load_system_host_keys()
현재 호스트의 ssh 키를 가져옵니다.
connect("hostname", username="username", password="password")
파라미터의 정보로 ssh 연결을 수립합니다.
exec_command("command")
연결된 ssh 커넥션으로 명령을 전달합니다.
리턴값으론 stdin, stdout, stderr가 리턴됩니다.
close()
ssh 연결을 종료합니다.
대화형(Interaction 쉘)
paramiko의 invoke_shell()을 통해 대화형 쉘에 접근할 수 있다.
from threading import Thread
import paramiko
import sys
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect("192.168.101.210", username="jhkim", password="asdf1346")
ssh = client.invoke_shell()
def recv_ssh(ssh):
while(ssh.closed == False):
sys.stdout.write(ssh.recv(10000).decode())
def send_ssh(ssh):
while(ssh.closed == False):
command = sys.stdin.readline()
ssh.send(command)
a = Thread(target=recv_ssh, args=[ssh])
b = Thread(target=send_ssh, args=[ssh])
a.start()
b.start()
Output
invoke_shell()
ssh 채널을 성립시킨 후, 해당 채널의 대화형 쉘을 요청한다
send_ssh(ssh)
해당 쉘로 명령을 보낸다.
recv_ssh(ssh)
해당 쉘로부터 받는 데이터를 출력시킨다.
두 작업을 두개의 쓰레드로 실행시켜, 마치 대화형 쉘처럼 동작하게 한다.