You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

499 lines
22 KiB

4 years ago
  1. '''This class extends pexpect.spawn to specialize setting up SSH connections.
  2. This adds methods for login, logout, and expecting the shell prompt.
  3. PEXPECT LICENSE
  4. This license is approved by the OSI and FSF as GPL-compatible.
  5. http://opensource.org/licenses/isc-license.txt
  6. Copyright (c) 2012, Noah Spurrier <noah@noah.org>
  7. PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
  8. PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
  9. COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  13. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  15. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  16. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. '''
  18. from pexpect import ExceptionPexpect, TIMEOUT, EOF, spawn
  19. import time
  20. import os
  21. import sys
  22. import re
  23. __all__ = ['ExceptionPxssh', 'pxssh']
  24. # Exception classes used by this module.
  25. class ExceptionPxssh(ExceptionPexpect):
  26. '''Raised for pxssh exceptions.
  27. '''
  28. if sys.version_info > (3, 0):
  29. from shlex import quote
  30. else:
  31. _find_unsafe = re.compile(r'[^\w@%+=:,./-]').search
  32. def quote(s):
  33. """Return a shell-escaped version of the string *s*."""
  34. if not s:
  35. return "''"
  36. if _find_unsafe(s) is None:
  37. return s
  38. # use single quotes, and put single quotes into double quotes
  39. # the string $'b is then quoted as '$'"'"'b'
  40. return "'" + s.replace("'", "'\"'\"'") + "'"
  41. class pxssh (spawn):
  42. '''This class extends pexpect.spawn to specialize setting up SSH
  43. connections. This adds methods for login, logout, and expecting the shell
  44. prompt. It does various tricky things to handle many situations in the SSH
  45. login process. For example, if the session is your first login, then pxssh
  46. automatically accepts the remote certificate; or if you have public key
  47. authentication setup then pxssh won't wait for the password prompt.
  48. pxssh uses the shell prompt to synchronize output from the remote host. In
  49. order to make this more robust it sets the shell prompt to something more
  50. unique than just $ or #. This should work on most Borne/Bash or Csh style
  51. shells.
  52. Example that runs a few commands on a remote server and prints the result::
  53. from pexpect import pxssh
  54. import getpass
  55. try:
  56. s = pxssh.pxssh()
  57. hostname = raw_input('hostname: ')
  58. username = raw_input('username: ')
  59. password = getpass.getpass('password: ')
  60. s.login(hostname, username, password)
  61. s.sendline('uptime') # run a command
  62. s.prompt() # match the prompt
  63. print(s.before) # print everything before the prompt.
  64. s.sendline('ls -l')
  65. s.prompt()
  66. print(s.before)
  67. s.sendline('df')
  68. s.prompt()
  69. print(s.before)
  70. s.logout()
  71. except pxssh.ExceptionPxssh as e:
  72. print("pxssh failed on login.")
  73. print(e)
  74. Example showing how to specify SSH options::
  75. from pexpect import pxssh
  76. s = pxssh.pxssh(options={
  77. "StrictHostKeyChecking": "no",
  78. "UserKnownHostsFile": "/dev/null"})
  79. ...
  80. Note that if you have ssh-agent running while doing development with pxssh
  81. then this can lead to a lot of confusion. Many X display managers (xdm,
  82. gdm, kdm, etc.) will automatically start a GUI agent. You may see a GUI
  83. dialog box popup asking for a password during development. You should turn
  84. off any key agents during testing. The 'force_password' attribute will turn
  85. off public key authentication. This will only work if the remote SSH server
  86. is configured to allow password logins. Example of using 'force_password'
  87. attribute::
  88. s = pxssh.pxssh()
  89. s.force_password = True
  90. hostname = raw_input('hostname: ')
  91. username = raw_input('username: ')
  92. password = getpass.getpass('password: ')
  93. s.login (hostname, username, password)
  94. `debug_command_string` is only for the test suite to confirm that the string
  95. generated for SSH is correct, using this will not allow you to do
  96. anything other than get a string back from `pxssh.pxssh.login()`.
  97. '''
  98. def __init__ (self, timeout=30, maxread=2000, searchwindowsize=None,
  99. logfile=None, cwd=None, env=None, ignore_sighup=True, echo=True,
  100. options={}, encoding=None, codec_errors='strict',
  101. debug_command_string=False):
  102. spawn.__init__(self, None, timeout=timeout, maxread=maxread,
  103. searchwindowsize=searchwindowsize, logfile=logfile,
  104. cwd=cwd, env=env, ignore_sighup=ignore_sighup, echo=echo,
  105. encoding=encoding, codec_errors=codec_errors)
  106. self.name = '<pxssh>'
  107. #SUBTLE HACK ALERT! Note that the command that SETS the prompt uses a
  108. #slightly different string than the regular expression to match it. This
  109. #is because when you set the prompt the command will echo back, but we
  110. #don't want to match the echoed command. So if we make the set command
  111. #slightly different than the regex we eliminate the problem. To make the
  112. #set command different we add a backslash in front of $. The $ doesn't
  113. #need to be escaped, but it doesn't hurt and serves to make the set
  114. #prompt command different than the regex.
  115. # used to match the command-line prompt
  116. self.UNIQUE_PROMPT = r"\[PEXPECT\][\$\#] "
  117. self.PROMPT = self.UNIQUE_PROMPT
  118. # used to set shell command-line prompt to UNIQUE_PROMPT.
  119. self.PROMPT_SET_SH = r"PS1='[PEXPECT]\$ '"
  120. self.PROMPT_SET_CSH = r"set prompt='[PEXPECT]\$ '"
  121. self.SSH_OPTS = ("-o'RSAAuthentication=no'"
  122. + " -o 'PubkeyAuthentication=no'")
  123. # Disabling host key checking, makes you vulnerable to MITM attacks.
  124. # + " -o 'StrictHostKeyChecking=no'"
  125. # + " -o 'UserKnownHostsFile /dev/null' ")
  126. # Disabling X11 forwarding gets rid of the annoying SSH_ASKPASS from
  127. # displaying a GUI password dialog. I have not figured out how to
  128. # disable only SSH_ASKPASS without also disabling X11 forwarding.
  129. # Unsetting SSH_ASKPASS on the remote side doesn't disable it! Annoying!
  130. #self.SSH_OPTS = "-x -o'RSAAuthentication=no' -o 'PubkeyAuthentication=no'"
  131. self.force_password = False
  132. self.debug_command_string = debug_command_string
  133. # User defined SSH options, eg,
  134. # ssh.otions = dict(StrictHostKeyChecking="no",UserKnownHostsFile="/dev/null")
  135. self.options = options
  136. def levenshtein_distance(self, a, b):
  137. '''This calculates the Levenshtein distance between a and b.
  138. '''
  139. n, m = len(a), len(b)
  140. if n > m:
  141. a,b = b,a
  142. n,m = m,n
  143. current = range(n+1)
  144. for i in range(1,m+1):
  145. previous, current = current, [i]+[0]*n
  146. for j in range(1,n+1):
  147. add, delete = previous[j]+1, current[j-1]+1
  148. change = previous[j-1]
  149. if a[j-1] != b[i-1]:
  150. change = change + 1
  151. current[j] = min(add, delete, change)
  152. return current[n]
  153. def try_read_prompt(self, timeout_multiplier):
  154. '''This facilitates using communication timeouts to perform
  155. synchronization as quickly as possible, while supporting high latency
  156. connections with a tunable worst case performance. Fast connections
  157. should be read almost immediately. Worst case performance for this
  158. method is timeout_multiplier * 3 seconds.
  159. '''
  160. # maximum time allowed to read the first response
  161. first_char_timeout = timeout_multiplier * 0.5
  162. # maximum time allowed between subsequent characters
  163. inter_char_timeout = timeout_multiplier * 0.1
  164. # maximum time for reading the entire prompt
  165. total_timeout = timeout_multiplier * 3.0
  166. prompt = self.string_type()
  167. begin = time.time()
  168. expired = 0.0
  169. timeout = first_char_timeout
  170. while expired < total_timeout:
  171. try:
  172. prompt += self.read_nonblocking(size=1, timeout=timeout)
  173. expired = time.time() - begin # updated total time expired
  174. timeout = inter_char_timeout
  175. except TIMEOUT:
  176. break
  177. return prompt
  178. def sync_original_prompt (self, sync_multiplier=1.0):
  179. '''This attempts to find the prompt. Basically, press enter and record
  180. the response; press enter again and record the response; if the two
  181. responses are similar then assume we are at the original prompt.
  182. This can be a slow function. Worst case with the default sync_multiplier
  183. can take 12 seconds. Low latency connections are more likely to fail
  184. with a low sync_multiplier. Best case sync time gets worse with a
  185. high sync multiplier (500 ms with default). '''
  186. # All of these timing pace values are magic.
  187. # I came up with these based on what seemed reliable for
  188. # connecting to a heavily loaded machine I have.
  189. self.sendline()
  190. time.sleep(0.1)
  191. try:
  192. # Clear the buffer before getting the prompt.
  193. self.try_read_prompt(sync_multiplier)
  194. except TIMEOUT:
  195. pass
  196. self.sendline()
  197. x = self.try_read_prompt(sync_multiplier)
  198. self.sendline()
  199. a = self.try_read_prompt(sync_multiplier)
  200. self.sendline()
  201. b = self.try_read_prompt(sync_multiplier)
  202. ld = self.levenshtein_distance(a,b)
  203. len_a = len(a)
  204. if len_a == 0:
  205. return False
  206. if float(ld)/len_a < 0.4:
  207. return True
  208. return False
  209. ### TODO: This is getting messy and I'm pretty sure this isn't perfect.
  210. ### TODO: I need to draw a flow chart for this.
  211. ### TODO: Unit tests for SSH tunnels, remote SSH command exec, disabling original prompt sync
  212. def login (self, server, username, password='', terminal_type='ansi',
  213. original_prompt=r"[#$]", login_timeout=10, port=None,
  214. auto_prompt_reset=True, ssh_key=None, quiet=True,
  215. sync_multiplier=1, check_local_ip=True,
  216. password_regex=r'(?i)(?:password:)|(?:passphrase for key)',
  217. ssh_tunnels={}, spawn_local_ssh=True,
  218. sync_original_prompt=True, ssh_config=None):
  219. '''This logs the user into the given server.
  220. It uses
  221. 'original_prompt' to try to find the prompt right after login. When it
  222. finds the prompt it immediately tries to reset the prompt to something
  223. more easily matched. The default 'original_prompt' is very optimistic
  224. and is easily fooled. It's more reliable to try to match the original
  225. prompt as exactly as possible to prevent false matches by server
  226. strings such as the "Message Of The Day". On many systems you can
  227. disable the MOTD on the remote server by creating a zero-length file
  228. called :file:`~/.hushlogin` on the remote server. If a prompt cannot be found
  229. then this will not necessarily cause the login to fail. In the case of
  230. a timeout when looking for the prompt we assume that the original
  231. prompt was so weird that we could not match it, so we use a few tricks
  232. to guess when we have reached the prompt. Then we hope for the best and
  233. blindly try to reset the prompt to something more unique. If that fails
  234. then login() raises an :class:`ExceptionPxssh` exception.
  235. In some situations it is not possible or desirable to reset the
  236. original prompt. In this case, pass ``auto_prompt_reset=False`` to
  237. inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh
  238. uses a unique prompt in the :meth:`prompt` method. If the original prompt is
  239. not reset then this will disable the :meth:`prompt` method unless you
  240. manually set the :attr:`PROMPT` attribute.
  241. Set ``password_regex`` if there is a MOTD message with `password` in it.
  242. Changing this is like playing in traffic, don't (p)expect it to match straight
  243. away.
  244. If you require to connect to another SSH server from the your original SSH
  245. connection set ``spawn_local_ssh`` to `False` and this will use your current
  246. session to do so. Setting this option to `False` and not having an active session
  247. will trigger an error.
  248. Set ``ssh_key`` to a file path to an SSH private key to use that SSH key
  249. for the session authentication.
  250. Set ``ssh_key`` to `True` to force passing the current SSH authentication socket
  251. to the desired ``hostname``.
  252. Set ``ssh_config`` to a file path string of an SSH client config file to pass that
  253. file to the client to handle itself. You may set any options you wish in here, however
  254. doing so will require you to post extra information that you may not want to if you
  255. run into issues.
  256. '''
  257. session_regex_array = ["(?i)are you sure you want to continue connecting", original_prompt, password_regex, "(?i)permission denied", "(?i)terminal type", TIMEOUT]
  258. session_init_regex_array = []
  259. session_init_regex_array.extend(session_regex_array)
  260. session_init_regex_array.extend(["(?i)connection closed by remote host", EOF])
  261. ssh_options = ''.join([" -o '%s=%s'" % (o, v) for (o, v) in self.options.items()])
  262. if quiet:
  263. ssh_options = ssh_options + ' -q'
  264. if not check_local_ip:
  265. ssh_options = ssh_options + " -o'NoHostAuthenticationForLocalhost=yes'"
  266. if self.force_password:
  267. ssh_options = ssh_options + ' ' + self.SSH_OPTS
  268. if ssh_config is not None:
  269. if spawn_local_ssh and not os.path.isfile(ssh_config):
  270. raise ExceptionPxssh('SSH config does not exist or is not a file.')
  271. ssh_options = ssh_options + '-F ' + ssh_config
  272. if port is not None:
  273. ssh_options = ssh_options + ' -p %s'%(str(port))
  274. if ssh_key is not None:
  275. # Allow forwarding our SSH key to the current session
  276. if ssh_key==True:
  277. ssh_options = ssh_options + ' -A'
  278. else:
  279. if spawn_local_ssh and not os.path.isfile(ssh_key):
  280. raise ExceptionPxssh('private ssh key does not exist or is not a file.')
  281. ssh_options = ssh_options + ' -i %s' % (ssh_key)
  282. # SSH tunnels, make sure you know what you're putting into the lists
  283. # under each heading. Do not expect these to open 100% of the time,
  284. # The port you're requesting might be bound.
  285. #
  286. # The structure should be like this:
  287. # { 'local': ['2424:localhost:22'], # Local SSH tunnels
  288. # 'remote': ['2525:localhost:22'], # Remote SSH tunnels
  289. # 'dynamic': [8888] } # Dynamic/SOCKS tunnels
  290. if ssh_tunnels!={} and isinstance({},type(ssh_tunnels)):
  291. tunnel_types = {
  292. 'local':'L',
  293. 'remote':'R',
  294. 'dynamic':'D'
  295. }
  296. for tunnel_type in tunnel_types:
  297. cmd_type = tunnel_types[tunnel_type]
  298. if tunnel_type in ssh_tunnels:
  299. tunnels = ssh_tunnels[tunnel_type]
  300. for tunnel in tunnels:
  301. if spawn_local_ssh==False:
  302. tunnel = quote(str(tunnel))
  303. ssh_options = ssh_options + ' -' + cmd_type + ' ' + str(tunnel)
  304. cmd = "ssh %s -l %s %s" % (ssh_options, username, server)
  305. if self.debug_command_string:
  306. return(cmd)
  307. # Are we asking for a local ssh command or to spawn one in another session?
  308. if spawn_local_ssh:
  309. spawn._spawn(self, cmd)
  310. else:
  311. self.sendline(cmd)
  312. # This does not distinguish between a remote server 'password' prompt
  313. # and a local ssh 'passphrase' prompt (for unlocking a private key).
  314. i = self.expect(session_init_regex_array, timeout=login_timeout)
  315. # First phase
  316. if i==0:
  317. # New certificate -- always accept it.
  318. # This is what you get if SSH does not have the remote host's
  319. # public key stored in the 'known_hosts' cache.
  320. self.sendline("yes")
  321. i = self.expect(session_regex_array)
  322. if i==2: # password or passphrase
  323. self.sendline(password)
  324. i = self.expect(session_regex_array)
  325. if i==4:
  326. self.sendline(terminal_type)
  327. i = self.expect(session_regex_array)
  328. if i==7:
  329. self.close()
  330. raise ExceptionPxssh('Could not establish connection to host')
  331. # Second phase
  332. if i==0:
  333. # This is weird. This should not happen twice in a row.
  334. self.close()
  335. raise ExceptionPxssh('Weird error. Got "are you sure" prompt twice.')
  336. elif i==1: # can occur if you have a public key pair set to authenticate.
  337. ### TODO: May NOT be OK if expect() got tricked and matched a false prompt.
  338. pass
  339. elif i==2: # password prompt again
  340. # For incorrect passwords, some ssh servers will
  341. # ask for the password again, others return 'denied' right away.
  342. # If we get the password prompt again then this means
  343. # we didn't get the password right the first time.
  344. self.close()
  345. raise ExceptionPxssh('password refused')
  346. elif i==3: # permission denied -- password was bad.
  347. self.close()
  348. raise ExceptionPxssh('permission denied')
  349. elif i==4: # terminal type again? WTF?
  350. self.close()
  351. raise ExceptionPxssh('Weird error. Got "terminal type" prompt twice.')
  352. elif i==5: # Timeout
  353. #This is tricky... I presume that we are at the command-line prompt.
  354. #It may be that the shell prompt was so weird that we couldn't match
  355. #it. Or it may be that we couldn't log in for some other reason. I
  356. #can't be sure, but it's safe to guess that we did login because if
  357. #I presume wrong and we are not logged in then this should be caught
  358. #later when I try to set the shell prompt.
  359. pass
  360. elif i==6: # Connection closed by remote host
  361. self.close()
  362. raise ExceptionPxssh('connection closed')
  363. else: # Unexpected
  364. self.close()
  365. raise ExceptionPxssh('unexpected login response')
  366. if sync_original_prompt:
  367. if not self.sync_original_prompt(sync_multiplier):
  368. self.close()
  369. raise ExceptionPxssh('could not synchronize with original prompt')
  370. # We appear to be in.
  371. # set shell prompt to something unique.
  372. if auto_prompt_reset:
  373. if not self.set_unique_prompt():
  374. self.close()
  375. raise ExceptionPxssh('could not set shell prompt '
  376. '(received: %r, expected: %r).' % (
  377. self.before, self.PROMPT,))
  378. return True
  379. def logout (self):
  380. '''Sends exit to the remote shell.
  381. If there are stopped jobs then this automatically sends exit twice.
  382. '''
  383. self.sendline("exit")
  384. index = self.expect([EOF, "(?i)there are stopped jobs"])
  385. if index==1:
  386. self.sendline("exit")
  387. self.expect(EOF)
  388. self.close()
  389. def prompt(self, timeout=-1):
  390. '''Match the next shell prompt.
  391. This is little more than a short-cut to the :meth:`~pexpect.spawn.expect`
  392. method. Note that if you called :meth:`login` with
  393. ``auto_prompt_reset=False``, then before calling :meth:`prompt` you must
  394. set the :attr:`PROMPT` attribute to a regex that it will use for
  395. matching the prompt.
  396. Calling :meth:`prompt` will erase the contents of the :attr:`before`
  397. attribute even if no prompt is ever matched. If timeout is not given or
  398. it is set to -1 then self.timeout is used.
  399. :return: True if the shell prompt was matched, False if the timeout was
  400. reached.
  401. '''
  402. if timeout == -1:
  403. timeout = self.timeout
  404. i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout)
  405. if i==1:
  406. return False
  407. return True
  408. def set_unique_prompt(self):
  409. '''This sets the remote prompt to something more unique than ``#`` or ``$``.
  410. This makes it easier for the :meth:`prompt` method to match the shell prompt
  411. unambiguously. This method is called automatically by the :meth:`login`
  412. method, but you may want to call it manually if you somehow reset the
  413. shell prompt. For example, if you 'su' to a different user then you
  414. will need to manually reset the prompt. This sends shell commands to
  415. the remote host to set the prompt, so this assumes the remote host is
  416. ready to receive commands.
  417. Alternatively, you may use your own prompt pattern. In this case you
  418. should call :meth:`login` with ``auto_prompt_reset=False``; then set the
  419. :attr:`PROMPT` attribute to a regular expression. After that, the
  420. :meth:`prompt` method will try to match your prompt pattern.
  421. '''
  422. self.sendline("unset PROMPT_COMMAND")
  423. self.sendline(self.PROMPT_SET_SH) # sh-style
  424. i = self.expect ([TIMEOUT, self.PROMPT], timeout=10)
  425. if i == 0: # csh-style
  426. self.sendline(self.PROMPT_SET_CSH)
  427. i = self.expect([TIMEOUT, self.PROMPT], timeout=10)
  428. if i == 0:
  429. return False
  430. return True
  431. # vi:ts=4:sw=4:expandtab:ft=python: