Paramiko
Paramiko is a pure-Python 1 (3.6+) implementation of the SSHv2 protocol 2, providing both client and server functionality. It provides the foundation for the high-level SSH library Fabric, which is what we recommend you use for common client use-cases such as running remote shell commands or transferring files.
SSH Agent 실행여부 확인
SSH_AGENT_PID
같은 환경변수로 확인할 수 없을 경우, 내부적으로 paramiko를 사용하므로 이걸로 확인하자.
SSH Tunneling Forward Example
sshtunnel 를 사용하는 방법도 있다.
import paramiko
import socket
import select
def handler(chan, host, port):
sock = socket.socket()
try:
sock.connect((host, port))
except Exception as e:
print(f"Forwarding request to {host}:{port} failed: {e}")
return
while True:
r, _, _ = select.select([sock, chan], [], [])
if sock in r:
data = sock.recv(1024)
if len(data) == 0:
break
chan.send(data)
if chan in r:
data = chan.recv(1024)
if len(data) == 0:
break
sock.send(data)
def forward_tunnel(local_port, remote_host, remote_port, transport):
transport.request_port_forward('localhost', local_port)
while True:
chan = transport.accept(1000)
if chan is None:
continue
handler(chan, remote_host, remote_port)
# Setup connection
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('ssh.example.com', username='your_username', password='your_password')
transport = client.get_transport()
forward_tunnel(10022, '127.0.0.1', 3306, transport)
Troubleshooting
SSH agent is not running or no keys are available
SSH Agent 가 실행되지 않을 경우 발생된다.
def prompt_for_key():
keys = paramiko.Agent().get_keys()
if not keys:
> raise SshAgentKeyError(SshAgentKeyError.E_NO_KEYS)
E sagecipher.cipher.SshAgentKeyError: SSH agent is not running or no keys are available
See also
- Sagecipher (SSH Agent 확인 용도로 사용한다)