PageRenderTime 50ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/IPython/external/ssh/tunnel.py

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