tunnel.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. """Basic ssh tunnel utilities, and convenience functions for tunneling
  2. zeromq connections.
  3. """
  4. # Copyright (C) 2010-2011 IPython Development Team
  5. # Copyright (C) 2011- PyZMQ Developers
  6. #
  7. # Redistributed from IPython under the terms of the BSD License.
  8. from __future__ import print_function
  9. import atexit
  10. import os
  11. import re
  12. import signal
  13. import socket
  14. import sys
  15. import warnings
  16. from getpass import getpass, getuser
  17. from multiprocessing import Process
  18. try:
  19. with warnings.catch_warnings():
  20. warnings.simplefilter('ignore', DeprecationWarning)
  21. import paramiko
  22. SSHException = paramiko.ssh_exception.SSHException
  23. except ImportError:
  24. paramiko = None
  25. class SSHException(Exception):
  26. pass
  27. else:
  28. from .forward import forward_tunnel
  29. try:
  30. import pexpect
  31. except ImportError:
  32. pexpect = None
  33. from ..utils.strtypes import b
  34. def select_random_ports(n):
  35. """Select and return n random ports that are available."""
  36. ports = []
  37. sockets = []
  38. for i in range(n):
  39. sock = socket.socket()
  40. sock.bind(('', 0))
  41. ports.append(sock.getsockname()[1])
  42. sockets.append(sock)
  43. for sock in sockets:
  44. sock.close()
  45. return ports
  46. #-----------------------------------------------------------------------------
  47. # Check for passwordless login
  48. #-----------------------------------------------------------------------------
  49. _password_pat = re.compile(b(r'pass(word|phrase):'), re.IGNORECASE)
  50. def try_passwordless_ssh(server, keyfile, paramiko=None):
  51. """Attempt to make an ssh connection without a password.
  52. This is mainly used for requiring password input only once
  53. when many tunnels may be connected to the same server.
  54. If paramiko is None, the default for the platform is chosen.
  55. """
  56. if paramiko is None:
  57. paramiko = sys.platform == 'win32'
  58. if not paramiko:
  59. f = _try_passwordless_openssh
  60. else:
  61. f = _try_passwordless_paramiko
  62. return f(server, keyfile)
  63. def _try_passwordless_openssh(server, keyfile):
  64. """Try passwordless login with shell ssh command."""
  65. if pexpect is None:
  66. raise ImportError("pexpect unavailable, use paramiko")
  67. cmd = 'ssh -f '+ server
  68. if keyfile:
  69. cmd += ' -i ' + keyfile
  70. cmd += ' exit'
  71. # pop SSH_ASKPASS from env
  72. env = os.environ.copy()
  73. env.pop('SSH_ASKPASS', None)
  74. ssh_newkey = 'Are you sure you want to continue connecting'
  75. p = pexpect.spawn(cmd, env=env)
  76. while True:
  77. try:
  78. i = p.expect([ssh_newkey, _password_pat], timeout=.1)
  79. if i==0:
  80. raise SSHException('The authenticity of the host can\'t be established.')
  81. except pexpect.TIMEOUT:
  82. continue
  83. except pexpect.EOF:
  84. return True
  85. else:
  86. return False
  87. def _try_passwordless_paramiko(server, keyfile):
  88. """Try passwordless login with paramiko."""
  89. if paramiko is None:
  90. msg = "Paramiko unavailable, "
  91. if sys.platform == 'win32':
  92. msg += "Paramiko is required for ssh tunneled connections on Windows."
  93. else:
  94. msg += "use OpenSSH."
  95. raise ImportError(msg)
  96. username, server, port = _split_server(server)
  97. client = paramiko.SSHClient()
  98. client.load_system_host_keys()
  99. client.set_missing_host_key_policy(paramiko.WarningPolicy())
  100. try:
  101. client.connect(server, port, username=username, key_filename=keyfile,
  102. look_for_keys=True)
  103. except paramiko.AuthenticationException:
  104. return False
  105. else:
  106. client.close()
  107. return True
  108. def tunnel_connection(socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60):
  109. """Connect a socket to an address via an ssh tunnel.
  110. This is a wrapper for socket.connect(addr), when addr is not accessible
  111. from the local machine. It simply creates an ssh tunnel using the remaining args,
  112. and calls socket.connect('tcp://localhost:lport') where lport is the randomly
  113. selected local port of the tunnel.
  114. """
  115. new_url, tunnel = open_tunnel(addr, server, keyfile=keyfile, password=password, paramiko=paramiko, timeout=timeout)
  116. socket.connect(new_url)
  117. return tunnel
  118. def open_tunnel(addr, server, keyfile=None, password=None, paramiko=None, timeout=60):
  119. """Open a tunneled connection from a 0MQ url.
  120. For use inside tunnel_connection.
  121. Returns
  122. -------
  123. (url, tunnel) : (str, object)
  124. The 0MQ url that has been forwarded, and the tunnel object
  125. """
  126. lport = select_random_ports(1)[0]
  127. transport, addr = addr.split('://')
  128. ip,rport = addr.split(':')
  129. rport = int(rport)
  130. if paramiko is None:
  131. paramiko = sys.platform == 'win32'
  132. if paramiko:
  133. tunnelf = paramiko_tunnel
  134. else:
  135. tunnelf = openssh_tunnel
  136. tunnel = tunnelf(lport, rport, server, remoteip=ip, keyfile=keyfile, password=password, timeout=timeout)
  137. return 'tcp://127.0.0.1:%i'%lport, tunnel
  138. def openssh_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60):
  139. """Create an ssh tunnel using command-line ssh that connects port lport
  140. on this machine to localhost:rport on server. The tunnel
  141. will automatically close when not in use, remaining open
  142. for a minimum of timeout seconds for an initial connection.
  143. This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
  144. as seen from `server`.
  145. keyfile and password may be specified, but ssh config is checked for defaults.
  146. Parameters
  147. ----------
  148. lport : int
  149. local port for connecting to the tunnel from this machine.
  150. rport : int
  151. port on the remote machine to connect to.
  152. server : str
  153. The ssh server to connect to. The full ssh server string will be parsed.
  154. user@server:port
  155. remoteip : str [Default: 127.0.0.1]
  156. The remote ip, specifying the destination of the tunnel.
  157. Default is localhost, which means that the tunnel would redirect
  158. localhost:lport on this machine to localhost:rport on the *server*.
  159. keyfile : str; path to public key file
  160. This specifies a key to be used in ssh login, default None.
  161. Regular default ssh keys will be used without specifying this argument.
  162. password : str;
  163. Your ssh password to the ssh server. Note that if this is left None,
  164. you will be prompted for it if passwordless key based login is unavailable.
  165. timeout : int [default: 60]
  166. The time (in seconds) after which no activity will result in the tunnel
  167. closing. This prevents orphaned tunnels from running forever.
  168. """
  169. if pexpect is None:
  170. raise ImportError("pexpect unavailable, use paramiko_tunnel")
  171. ssh="ssh "
  172. if keyfile:
  173. ssh += "-i " + keyfile
  174. if ':' in server:
  175. server, port = server.split(':')
  176. ssh += " -p %s" % port
  177. cmd = "%s -O check %s" % (ssh, server)
  178. (output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
  179. if not exitstatus:
  180. pid = int(output[output.find(b"(pid=")+5:output.find(b")")])
  181. cmd = "%s -O forward -L 127.0.0.1:%i:%s:%i %s" % (
  182. ssh, lport, remoteip, rport, server)
  183. (output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
  184. if not exitstatus:
  185. atexit.register(_stop_tunnel, cmd.replace("-O forward", "-O cancel", 1))
  186. return pid
  187. cmd = "%s -f -S none -L 127.0.0.1:%i:%s:%i %s sleep %i" % (
  188. ssh, lport, remoteip, rport, server, timeout)
  189. # pop SSH_ASKPASS from env
  190. env = os.environ.copy()
  191. env.pop('SSH_ASKPASS', None)
  192. ssh_newkey = 'Are you sure you want to continue connecting'
  193. tunnel = pexpect.spawn(cmd, env=env)
  194. failed = False
  195. while True:
  196. try:
  197. i = tunnel.expect([ssh_newkey, _password_pat], timeout=.1)
  198. if i==0:
  199. raise SSHException('The authenticity of the host can\'t be established.')
  200. except pexpect.TIMEOUT:
  201. continue
  202. except pexpect.EOF:
  203. if tunnel.exitstatus:
  204. print(tunnel.exitstatus)
  205. print(tunnel.before)
  206. print(tunnel.after)
  207. raise RuntimeError("tunnel '%s' failed to start"%(cmd))
  208. else:
  209. return tunnel.pid
  210. else:
  211. if failed:
  212. print("Password rejected, try again")
  213. password=None
  214. if password is None:
  215. password = getpass("%s's password: "%(server))
  216. tunnel.sendline(password)
  217. failed = True
  218. def _stop_tunnel(cmd):
  219. pexpect.run(cmd)
  220. def _split_server(server):
  221. if '@' in server:
  222. username,server = server.split('@', 1)
  223. else:
  224. username = getuser()
  225. if ':' in server:
  226. server, port = server.split(':')
  227. port = int(port)
  228. else:
  229. port = 22
  230. return username, server, port
  231. def paramiko_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60):
  232. """launch a tunner with paramiko in a subprocess. This should only be used
  233. when shell ssh is unavailable (e.g. Windows).
  234. This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
  235. as seen from `server`.
  236. If you are familiar with ssh tunnels, this creates the tunnel:
  237. ssh server -L localhost:lport:remoteip:rport
  238. keyfile and password may be specified, but ssh config is checked for defaults.
  239. Parameters
  240. ----------
  241. lport : int
  242. local port for connecting to the tunnel from this machine.
  243. rport : int
  244. port on the remote machine to connect to.
  245. server : str
  246. The ssh server to connect to. The full ssh server string will be parsed.
  247. user@server:port
  248. remoteip : str [Default: 127.0.0.1]
  249. The remote ip, specifying the destination of the tunnel.
  250. Default is localhost, which means that the tunnel would redirect
  251. localhost:lport on this machine to localhost:rport on the *server*.
  252. keyfile : str; path to public key file
  253. This specifies a key to be used in ssh login, default None.
  254. Regular default ssh keys will be used without specifying this argument.
  255. password : str;
  256. Your ssh password to the ssh server. Note that if this is left None,
  257. you will be prompted for it if passwordless key based login is unavailable.
  258. timeout : int [default: 60]
  259. The time (in seconds) after which no activity will result in the tunnel
  260. closing. This prevents orphaned tunnels from running forever.
  261. """
  262. if paramiko is None:
  263. raise ImportError("Paramiko not available")
  264. if password is None:
  265. if not _try_passwordless_paramiko(server, keyfile):
  266. password = getpass("%s's password: "%(server))
  267. p = Process(target=_paramiko_tunnel,
  268. args=(lport, rport, server, remoteip),
  269. kwargs=dict(keyfile=keyfile, password=password))
  270. p.daemon = True
  271. p.start()
  272. return p
  273. def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
  274. """Function for actually starting a paramiko tunnel, to be passed
  275. to multiprocessing.Process(target=this), and not called directly.
  276. """
  277. username, server, port = _split_server(server)
  278. client = paramiko.SSHClient()
  279. client.load_system_host_keys()
  280. client.set_missing_host_key_policy(paramiko.WarningPolicy())
  281. try:
  282. client.connect(server, port, username=username, key_filename=keyfile,
  283. look_for_keys=True, password=password)
  284. # except paramiko.AuthenticationException:
  285. # if password is None:
  286. # password = getpass("%s@%s's password: "%(username, server))
  287. # client.connect(server, port, username=username, password=password)
  288. # else:
  289. # raise
  290. except Exception as e:
  291. print('*** Failed to connect to %s:%d: %r' % (server, port, e))
  292. sys.exit(1)
  293. # Don't let SIGINT kill the tunnel subprocess
  294. signal.signal(signal.SIGINT, signal.SIG_IGN)
  295. try:
  296. forward_tunnel(lport, remoteip, rport, client.get_transport())
  297. except KeyboardInterrupt:
  298. print('SIGINT: Port forwarding stopped cleanly')
  299. sys.exit(0)
  300. except Exception as e:
  301. print("Port forwarding stopped uncleanly: %s"%e)
  302. sys.exit(255)
  303. if sys.platform == 'win32':
  304. ssh_tunnel = paramiko_tunnel
  305. else:
  306. ssh_tunnel = openssh_tunnel
  307. __all__ = ['tunnel_connection', 'ssh_tunnel', 'openssh_tunnel', 'paramiko_tunnel', 'try_passwordless_ssh']