Advertisement
Guest User

Untitled

a guest
Mar 1st, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. def execute_command_ssh(device, commands, root_required=False, print_exit_code=False, exception_if_failed=False,
  2.                         hide_output=False):
  3.     if not is_nonstring_iterable(commands) or isinstance(commands, basestring):
  4.         commands = [commands]
  5.     sudopass = Responder(pattern=r'Password:', response='{}\n'.format(device.determineRootPassword()))
  6.     dict_response = {}
  7.     with Connection(device.host, user=device.username, port=22, connect_kwargs={"password": device.password}) as device_ssh:
  8.         for command in commands:
  9.             dict_command = command
  10.             if root_required:
  11.                 command = "su -c '{}'".format(command)
  12.             print("Executing command {}".format(command))
  13.             if exception_if_failed:
  14.                 print("Response is:")
  15.             try:
  16.                 output = device_ssh.run(command, pty=True, hide=hide_output, watchers=[sudopass])
  17.             except invoke_exception.UnexpectedExit as err:
  18.                 if exception_if_failed:
  19.                     raise ProblemOccuredWhileExecutingCommand(command, err, err.result.exited)
  20.                 else:
  21.                     message = "Unexpected exit while executing command {}".format(command)
  22.                     exit_code = err.result.exited
  23.                     response = err.result.stdout.strip()
  24.             else:
  25.                 message = "Command {} executed".format(output.command)
  26.                 exit_code = output.exited
  27.                 response = str(output.stdout.strip())  # by default output.stdout is unicode, not string
  28.             print(message)
  29.             if print_exit_code:
  30.                 print("Exit code is: {}".format(exit_code))
  31.             if response.startswith("Password:"):
  32.                 response = re.sub('Password: \r\n', '', response)
  33.             dict_response[dict_command] = (exit_code, response)
  34.     return dict_response
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement