Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def execute_command_ssh(device, commands, root_required=False, print_exit_code=False, exception_if_failed=False,
- hide_output=False):
- if not is_nonstring_iterable(commands) or isinstance(commands, basestring):
- commands = [commands]
- sudopass = Responder(pattern=r'Password:', response='{}\n'.format(device.determineRootPassword()))
- dict_response = {}
- with Connection(device.host, user=device.username, port=22, connect_kwargs={"password": device.password}) as device_ssh:
- for command in commands:
- dict_command = command
- if root_required:
- command = "su -c '{}'".format(command)
- print("Executing command {}".format(command))
- if exception_if_failed:
- print("Response is:")
- try:
- output = device_ssh.run(command, pty=True, hide=hide_output, watchers=[sudopass])
- except invoke_exception.UnexpectedExit as err:
- if exception_if_failed:
- raise ProblemOccuredWhileExecutingCommand(command, err, err.result.exited)
- else:
- message = "Unexpected exit while executing command {}".format(command)
- exit_code = err.result.exited
- response = err.result.stdout.strip()
- else:
- message = "Command {} executed".format(output.command)
- exit_code = output.exited
- response = str(output.stdout.strip()) # by default output.stdout is unicode, not string
- print(message)
- if print_exit_code:
- print("Exit code is: {}".format(exit_code))
- if response.startswith("Password:"):
- response = re.sub('Password: \r\n', '', response)
- dict_response[dict_command] = (exit_code, response)
- return dict_response
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement