如何使用python打开SSH隧道?
问题描述:
我想用django连接到远程mysql数据库。
该文档指定需要首先打开SSH隧道才能连接到数据库。
是否有一个python库,只要设置了某些设置,就可以打开SSH隧道?如何使用python打开SSH隧道?
答
以下是Python3的代码片段(但您应该可以毫无困难地将其改装为Python2)。它在一个单独的线程中运行SSH隧道;那么主线程会通过SSH隧道获取网络流量。
在本例中,ssh隧道将本地端口2222转发到localhost上的端口80。主要活动包括运行
curl http://localhost:2222
即,获取的网页,但从端口2222
类SshTunnel用4个参数,本地和远程端口,远程用户,并且远程初始化主办。它所做的,是通过以下方式启动SSH:
ssh -N -L localport:remotehost:remoteport [email protected]
为了使这项工作,你所需要的remoteuser表@远程主机密码登录少(通过的〜/ .ssh/id_rsa.pub这在远程服务器上已知)。 因此正在运行的ssh隧道在一个线程上;主要任务必须在另一个。 ssh隧道线程被标记为守护进程,以便主活动终止后它会自动停止。
我没有提供完整的MySQL连接示例,因为它应该是不言自明的。一旦SshTunnel建立了一个本地TCP端口,你就可以连接到它 - 无论是通过你的MySQL客户端,卷曲还是其他任何东西。
import subprocess
import time
import threading
class SshTunnel(threading.Thread):
def __init__(self, localport, remoteport, remoteuser, remotehost):
threading.Thread.__init__(self)
self.localport = localport # Local port to listen to
self.remoteport = remoteport # Remote port on remotehost
self.remoteuser = remoteuser # Remote user on remotehost
self.remotehost = remotehost # What host do we send traffic to
self.daemon = True # So that thread will exit when
# main non-daemon thread finishes
def run(self):
if subprocess.call([
'ssh', '-N',
'-L', str(self.localport) + ':' + self.remotehost + ':' + str(self.remoteport),
self.remoteuser + '@' + self.remotehost ]):
raise Exception ('ssh tunnel setup failed')
if __name__ == '__main__':
tunnel = SshTunnel(2222, 80, 'karel', 'localhost')
tunnel.start()
time.sleep(1)
subprocess.call(['curl', 'http://localhost:2222'])
答
尝试使用sshtunnel package。
这很简单:
pip install sshtunnel
python -m sshtunnel -U vagrant -P vagrant -L :3306 -R 127.0.0.1:3306 -p 2222 localhost
答
这里有一个小的类,你可以拖放到你的代码:
import subprocess
import random
import tempfile
class SSHTunnel:
def __init__(self, host, user, port, key, remote_port):
self.host = host
self.user = user
self.port = port
self.key = key
self.remote_port = remote_port
# Get a temporary file name
tmpfile = tempfile.NamedTemporaryFile()
tmpfile.close()
self.socket = tmpfile.name
self.local_port = random.randint(10000, 65535)
self.local_host = '127.0.0.1'
self.open = False
def start(self):
exit_status = subprocess.call(['ssh', '-MfN',
'-S', self.socket,
'-i', self.key,
'-p', self.port,
'-l', self.user,
'-L', '{}:{}:{}'.format(self.local_port, self.local_host, self.remote_port),
'-o', 'ExitOnForwardFailure=True',
self.host
])
if exit_status != 0:
raise Exception('SSH tunnel failed with status: {}'.format(exit_status))
if self.send_control_command('check') != 0:
raise Exception('SSH tunnel failed to check')
self.open = True
def stop(self):
if self.open:
if self.send_control_command('exit') != 0:
raise Exception('SSH tunnel failed to exit')
self.open = False
def send_control_command(self, cmd):
return subprocess.check_call(['ssh', '-S', self.socket, '-O', cmd, '-l', self.user, self.host])
def __enter__(self):
self.start()
return self
def __exit__(self, type, value, traceback):
self.stop()
而且这里是你如何能与MySQL(3306端口经常使用,例如):
with SSHTunnel('database.server.com', 'you', '22', '/path/to/private_key', '3306') as tunnel:
print "Connected on port {} at {}".format(tunnel.local_port, tunnel.local_host)
http://stackoverflow.com/questions/953477/ssh-connection-with-python-3-0 – 2010-12-06 08:10:57
尝试https:///github.com/pahaz/sshtunnel – pahaz 2016-02-11 09:42:00