
원격 서버로의 SSH 터널
|테스트| |AppVeyor| |readthedocs| |coveralls| |버전|
|pyversions| |라이선스|
작성자: Pahaz_
저장소: https://github.com/pahaz/sshtunnel/
Windows에서 작동하지 않는 https://github.com/jmagnusson/bgtunnel에서 영감을 받았습니다.
참고: https://github.com/paramiko/paramiko/blob/master/demos/forward.py
paramiko_sshtunnel_은 PyPI에 있으므로 간단히 실행하세요:
::
pip install sshtunnel
또는 ::
easy_install sshtunnel
또는 ::
conda install -c conda-forge sshtunnel
를 실행하면 환경에 설치됩니다.
소스에서 설치하려면 저장소 <https://github.com/pahaz/sshtunnel>_를 복제한 후 실행하세요::
python setup.py install
테스트를 실행하려면 먼저 tox <https://testrun.org/tox/latest/>_가 필요하며, 다음을 실행하세요::
python setup.py test
sshtunnel이 유용한 대표적인 시나리오 중 하나는 아래 그림에 나와 있습니다. 사용자는 SSH 포트(보통 22번 포트)만 접근 가능한 원격 서버의 포트(예: 8080)에 연결해야 할 수 있습니다. ::
----------------------------------------------------------------------
|
-------------+ | +----------+
LOCAL | | | REMOTE | :22 SSH
CLIENT | <== SSH ========> | SERVER | :8080 web service
-------------+ | +----------+
|
FIREWALL (only port 22 is open)
----------------------------------------------------------------------
그림1: SSH 터널을 통해 방화벽으로 차단된 서비스에 연결하는 방법.
SSH 서버가 허용하는 경우, 외부(LOCAL CLIENT 관점)에서 직접 보이지 않는 사설 서버(REMOTE SERVER 관점)에 접근하는 것도 가능합니다. ::
----------------------------------------------------------------------
|
-------------+ | +----------+ +---------
LOCAL | | | REMOTE | | PRIVATE
CLIENT | <== SSH ========> | SERVER | <== local ==> | SERVER
-------------+ | +----------+ +---------
|
FIREWALL (only port 443 is open)
----------------------------------------------------------------------
그림2: SSH 터널을 통해 PRIVATE SERVER에 연결하는 방법.
API는 터널을 초기화하고 시작하거나, 터널을 시작하고 중지하는 작업을 처리하는 with 컨텍스트를 사용할 수 있게 해줍니다:
위의 그림1에 해당하는 코드는 다음과 같으며, 원격 서버 주소는 pahaz.urfuclub.ru, 비밀번호 인증, 무작위로 할당된 로컬 바인드 포트를 사용합니다.
.. code-block:: python
from sshtunnel import SSHTunnelForwarder
server = SSHTunnelForwarder(
'alfa.8iq.dev',
ssh_username="pahaz",
ssh_password="secret",
remote_bind_address=('127.0.0.1', 8080)
)
server.start()
print(server.local_bind_port) # show assigned local port
# work with `SECRET SERVICE` through `server.local_bind_port`.
server.stop()
직접 접근할 수 없는 사설 서버로의 포트 포워딩 예제로, 비밀번호로 보호된 pkey 인증을 가정하며, 원격 서버의 SSH 서비스가 443번 포트에서 수신 중이고 해당 포트가 방화벽에서 열려 있다고 가정합니다(그림2):
.. code-block:: python
import paramiko
import sshtunnel
with sshtunnel.open_tunnel(
(REMOTE_SERVER_IP, 443),
ssh_username="",
ssh_pkey="/var/ssh/rsa_key",
ssh_private_key_password="secret",
remote_bind_address=(PRIVATE_SERVER_IP, 22),
local_bind_address=('0.0.0.0', 10022)
) as tunnel:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('127.0.0.1', 10022)
# do some operations with client session
client.close()
print('FINISH!')
Vagrant MySQL 로컬 포트에 대한 포트 포워딩 예제:
.. code-block:: python
from sshtunnel import open_tunnel
from time import sleep
with open_tunnel(
('localhost', 2222),
ssh_username="vagrant",
ssh_password="vagrant",
remote_bind_address=('127.0.0.1', 3306)
) as server:
print(server.local_bind_port)
while True:
# press Ctrl-C for stopping
sleep(1)
print('FINISH!')
또는 간단히 CLI를 사용하여:
.. code-block:: console
(bash)$ python -m sshtunnel -U vagrant -P vagrant -L :3306 -R 127.0.0.1:3306 -p 2222 localhost
두 개의 터널을 거쳐 점프하는 SSH 세션 열기. SSH 전송과 터널은 데몬화되며, 종료 시 연결이 중지되기를 기다리지 않습니다.
.. code-block:: python
import sshtunnel
from paramiko import SSHClient
with sshtunnel.open_tunnel(
ssh_address_or_host=('GW1_ip', 20022),
remote_bind_address=('GW2_ip', 22),
) as tunnel1:
print('Connection to tunnel1 (GW1_ip:GW1_port) OK...')
with sshtunnel.open_tunnel(
ssh_address_or_host=('localhost', tunnel1.local_bind_port),
remote_bind_address=('target_ip', 22),
ssh_username='GW2_user',
ssh_password='GW2_pwd',
) as tunnel2:
print('Connection to tunnel2 (GW2_ip:GW2_port) OK...')
with SSHClient() as ssh:
ssh.connect('localhost',
port=tunnel2.local_bind_port,
username='target_user',
password='target_pwd',
)
ssh.exec_command(...)
::
$ sshtunnel --help
usage: sshtunnel [-h] [-U SSH_USERNAME] [-p SSH_PORT] [-P SSH_PASSWORD] -R
IP:PORT [IP:PORT ...] [-L [IP:PORT ...]] [-k SSH_HOST_KEY]
[-K KEY_FILE] [-S KEY_PASSWORD] [-t] [-v] [-V] [-x IP:PORT]
[-c SSH_CONFIG_FILE] [-z] [-n] [-d [FOLDER ...]]
ssh_address
Pure python ssh tunnel utils
Version 0.5.1
positional arguments:
ssh_address SSH server IP address (GW for SSH tunnels)
set with "-- ssh_address" if immediately after -R or -L
options:
-h, --help 이 도움말 메시지를 표시하고 종료
-U SSH_USERNAME, --username SSH_USERNAME
SSH 서버 계정 사용자 이름
-p SSH_PORT, --server_port SSH_PORT
SSH 서버 TCP 포트 (기본값: 22)
-P SSH_PASSWORD, --password SSH_PASSWORD
SSH 서버 계정 비밀번호
-R IP:PORT [IP:PORT ...], --remote_bind_address IP:PORT [IP:PORT ...]
원격 바인드 주소 시퀀스: ip_1:port_1 ip_2:port_2 ... ip_n:port_n
ssh -Lxxxx:IP_ADDRESS:PORT와 동일
포트를 생략하면 기본값은 22입니다.
예: -R 10.10.10.10: 10.10.10.10:5900
-L [IP:PORT ...], --local_bind_address [IP:PORT ...]
로컬 바인드 주소 시퀀스: ip_1:port_1 ip_2:port_2 ... ip_n:port_n
요소는 유효한 UNIX 소켓 도메인일 수도 있습니다:
/tmp/foo.sock /tmp/bar.sock ... /tmp/baz.sock
ssh -LPORT:xxxxxxxxx:xxxx와 동일하며, 로컬 IP 주소는 선택 사항입니다.
기본적으로 모든 인터페이스(0.0.0.0)에서 수신 대기하고 임의의 포트를 선택합니다.
예: -L :40000
-k SSH_HOST_KEY, --ssh_host_key SSH_HOST_KEY
게이트웨이의 호스트 키
-K KEY_FILE, --private_key_file KEY_FILE
RSA/DSS/ECDSA 개인 키 파일
-S KEY_PASSWORD, --private_key_password KEY_PASSWORD
RSA/DSS/ECDSA 개인 키 비밀번호
-t, --threaded 각 터널에 대한 동시 연결 허용
-v, --verbose 출력 상세 수준 증가 (기본값: ERROR)
-V, --version 버전 번호를 표시하고 종료
-x IP:PORT, --proxy IP:PORT
대상으로 향하는 SSH 프록시의 IP 및 포트
-c SSH_CONFIG_FILE, --config SSH_CONFIG_FILE
SSH 구성 파일, 기본값은 ~/.ssh/config
-z, --compress SSH 전송을 통한 압축을 서버에 요청
-n, --noagent SSH 에이전트에서 키를 찾지 않음
-d [FOLDER ...], --host_pkey_directories [FOLDER ...]
SSH pkey(`id_*` 형식)를 찾을 수 있는 디렉터리 목록