def init_ssh_client(self):
self.log.debug("SSHProtocol: Initializing the destination transport")
self.destt = paramiko.Transport(self.destination)
try:
self.destt.start_client()
except paramiko.SSHException:
self.log.error("*** SSH negotiation failed.")
return
python类SSHException()的实例源码
def exec_cmd(self, ip_addr, username, password, cmd,
ssh_log=None, look_for_keys=True, key_filename=None):
if ssh_log is not None:
self.SSH_LOG = ssh_log
if self.log.get_level() == Logger.DEBUG:
paramiko.util.log_to_file(self.SSH_LOG)
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(
ip_addr,
port=self.SWITCH_PORT,
username=username,
password=password,
look_for_keys=look_for_keys,
key_filename=key_filename)
except (
paramiko.BadHostKeyException,
paramiko.AuthenticationException,
paramiko.SSHException,
socket.error,
BaseException) as exc:
self.log.error('%s: %s' % (ip_addr, str(exc)))
raise SSH_Exception('SSH connection Failure - {}'.format(exc))
# sys.exit(1)
try:
_, stdout, stderr = ssh.exec_command(cmd)
except paramiko.SSHException as exc:
self.log.error('%s: %s, %s' % (ip_addr, str(exc), stderr.read()))
sys.exit(1)
stdout_ = stdout.read()
stderr_ = stderr.read()
status = stdout.channel.recv_exit_status()
ssh.close()
return status, stdout_, stderr_
def __init__(self, host, log=None, ssh_log=None, username=None,
password=None, look_for_keys=True, key_filename=None):
paramiko.SSHClient.__init__(self)
self.host = host
self.log = log
self.ssh_log = ssh_log
if ssh_log is not None:
paramiko.util.log_to_file(ssh_log)
elif log is not None:
if self.log.get_level() == Logger.DEBUG:
ssh_log = FILE_PATH[:FILE_PATH.rfind('/')]
ssh_log += '/ssh_paramiko.log'
paramiko.util.log_to_file(ssh_log)
if key_filename is None:
self.load_system_host_keys()
self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
self.connect(
host,
username=username,
password=password,
look_for_keys=look_for_keys,
key_filename=key_filename)
except (
paramiko.BadHostKeyException,
paramiko.AuthenticationException,
paramiko.SSHException,
socket.error,
BaseException) as exc:
if log is not None:
self.log.error('%s: %s' % (host, str(exc)))
else:
print('%s: %s' % (host, str(exc)))
raise SSH_Exception('Connection Failure - {}'.format(exc))
def send_cmd(self, cmd):
try:
_, stdout, stderr = self.exec_command(cmd)
except paramiko.SSHException as exc:
if self.log is not None:
self.log.error('%s: %s' % (self.host, str(exc)))
else:
print('%s: %s' % (self.host, str(exc)))
sys.exit(1)
stdout_ = stdout.read()
stderr_ = stderr.read()
status = stdout.channel.recv_exit_status()
return status, stdout_, stderr_
def check_channel_exec_request(self, channel, command):
if not self.upstream or not self.upstream.allow_ssh:
return False
try:
self.shellchannel.exec_command(command)
self.shellthread = pysshrp.SSHInterface(channel, self.shellchannel)
self.shellthread.start()
self.logger.info('%s:%d: new exec requested' % self.client_address)
return True
except paramiko.SSHException:
self.logger.critical('%s:%d: exec request failed' % self.client_address)
return False
def check_channel_shell_request(self, channel):
if not self.upstream or not self.upstream.allow_ssh:
return False
try:
self.shellchannel.invoke_shell()
self.shellthread = pysshrp.SSHInterface(channel, self.shellchannel)
self.shellthread.start()
self.logger.info('%s:%d: new shell requested' % self.client_address)
return True
except paramiko.SSHException:
self.logger.critical('%s:%d: shell request failed' % self.client_address)
return False
def check_channel_pty_request(self, channel, term, width, height, pixelwidth, pixelheight, modes):
if not self.upstream or not self.upstream.allow_ssh:
return False
try:
self.shellchannel.get_pty(term, width, height, pixelwidth, pixelheight)
self.logger.info('%s:%d: new pty requested' % self.client_address)
return True
except paramiko.SSHException:
self.logger.critical('%s:%d: pty request failed' % self.client_address)
return False
def check_channel_subsystem_request(self, channel, name):
if not self.upstream or not self.upstream.allow_sftp:
return False
try:
super(ClientThread, self).check_channel_subsystem_request(channel, name)
self.logger.info('%s:%d: new subsystem "%s" requested' % (self.client_address + (name,)))
return True
except paramiko.SSHException:
self.logger.critical('%s:%d: subsystem "%s" request failed' % (self.client_address + (name,)))
return False
def __init__(self, *args, **kwargs):
for key, value in kwargs.items():
if (key == 'user') and not isinstance(value, str):
raise ConfigurationException('value of "user" must be a string')
elif (key == 'password') and not isinstance(value, str):
raise ConfigurationException('value of "password" must be a string')
elif (key == 'upstream_host') and not isinstance(value, str):
raise ConfigurationException('value of "upstream_host" must be a string')
elif (key == 'upstream_user') and not isinstance(value, str):
raise ConfigurationException('value of "upstream_user" must be a string')
elif (key == 'upstream_password') and not isinstance(value, str):
raise ConfigurationException('value of "upstream_password" must be a string')
elif (key == 'upstream_key') and not isinstance(value, str):
raise ConfigurationException('value of "upstream_key" must be a string')
elif (key == 'upstream_authorized_keys') and not isinstance(value, str):
raise ConfigurationException('value of "upstream_authorized_keys" must be a string')
elif (key == 'upstream_port') and not isinstance(value, int):
raise ConfigurationException('value of "upstream_port" must be an integer')
elif (key == 'upstream_root_path') and not isinstance(value, str):
raise ConfigurationException('value of "upstream_root_path" must be a string')
elif (key == 'allow_ssh') and not isinstance(value, bool):
raise ConfigurationException('value of "allow_ssh" must be a boolean')
elif (key == 'allow_sftp') and not isinstance(value, bool):
raise ConfigurationException('value of "allow_sftp" must be a boolean')
setattr(self, key, value)
# Additional configuration
if not self.user:
raise pysshrp.PysshrpException('"user" is mandatory in "servers"')
if not self.upstream_host:
raise pysshrp.PysshrpException('"upstream_host" is mandatory in "servers"')
if self.upstream_key:
try:
self.upstream_key = paramiko.RSAKey.from_private_key_file(self.upstream_key)
except IOError:
raise pysshrp.PysshrpException('failed to open SSH key file "%s"' % self.upstream_key)
except paramiko.SSHException:
raise pysshrp.PysshrpException('invalid SSH key from "%s"' % self.upstream_key)
def installserver(self):
self.endserver()
sleep(self.parameters['delay'])
self.ssh.ask('rw')
sleep(self.parameters['delay'])
self.ssh.ask('mkdir ' + self.parameters['serverdirname'])
sleep(self.parameters['delay'])
self.ssh.ask("cd " + self.parameters['serverdirname'])
#try both versions
for serverfile in ['monitor_server','monitor_server_0.95']:
sleep(self.parameters['delay'])
try:
self.ssh.scp.put(
os.path.join(os.path.abspath(os.path.dirname(__file__)), 'monitor_server', serverfile),
self.parameters['serverdirname'] + self.parameters['monitor_server_name'])
except (SCPException, SSHException):
self.logger.exception("Upload error. Try again after rebooting your RedPitaya..")
sleep(self.parameters['delay'])
self.ssh.ask('chmod 755 ./'+self.parameters['monitor_server_name'])
sleep(self.parameters['delay'])
self.ssh.ask('ro')
result = self.ssh.ask("./"+self.parameters['monitor_server_name']+" "+ str(self.parameters['port']))
sleep(self.parameters['delay'])
result += self.ssh.ask()
if not "sh" in result:
self.logger.debug("Server application started on port %d",
self.parameters['port'])
return self.parameters['port']
else: # means we tried the wrong binary version. make sure server is not running and try again with next file
self.endserver()
#try once more on a different port
if self.parameters['port'] == self.parameters['defaultport']:
self.parameters['port'] = random.randint(self.parameters['defaultport'],50000)
self.logger.warning("Problems to start the server application. Trying again with a different port number %d",self.parameters['port'])
return self.installserver()
self.logger.error("Server application could not be started. Try to recompile monitor_server on your RedPitaya (see manual). ")
return None
def run(self, command):
"""
Run a command on the remote host.
:type command: string
:param command: The command that you want to send to the remote host.
:rtype: tuple
:return: This function returns a tuple that contains an integer status,
the stdout from the command, and the stderr from the command.
"""
boto.log.debug('running:%s on %s' % (command, self.server.instance_id))
status = 0
try:
t = self._ssh_client.exec_command(command)
except paramiko.SSHException:
status = 1
std_out = t[1].read()
std_err = t[2].read()
t[0].close()
t[1].close()
t[2].close()
boto.log.debug('stdout: %s' % std_out)
boto.log.debug('stderr: %s' % std_err)
return (status, std_out, std_err)
def add_device(args):
ssh_key_string = None
if args.key:
try:
(ssh_key_string, password) = _read_key_file(args.key, args.password)
except (IOError, paramiko.SSHException) as e:
message = _("Error reading key file: %s") % e
return -1, message
elif args.password:
password = args.password
else:
new_password = getpass.getpass(_("Device password:"))
if not new_password:
message = _("Please input a valid password and retry the command.")
return -1, message
password = new_password
rack_id = None
if args.rack:
rack_id = rack_mgr.get_rack_id_by_label(args.rack)
if rack_id is None:
error_message = _("Rack label (%s) was not found.") % args.rack
return -1, error_message
return resource_mgr.add_resource(args.label, args.type, args.address, args.user,
password, rack_id, args.rack_location, ssh_key_string)
def change_device(args):
ssh_key_string = None
if args.key:
try:
(ssh_key_string, password) = _read_key_file(args.key, args.password)
except (IOError, paramiko.SSHException) as e:
message = _("Error reading key file: %s") % e
return -1, message
elif args.prompt_password:
new_password = getpass.getpass(_("Device password:"))
if not new_password:
message = _("Please input a valid password and retry the command.")
return -1, message
password = new_password
else:
password = args.password
rackid = None
if args.rack:
rackid = rack_mgr.get_rack_id_by_label(args.rack)
if rackid is None:
message = _("Input label for rack option (%s) not found.") % (args.rack)
return -1, message
if (not password and not args.address and not args.new_label and not
rackid and not args.rack_location and not ssh_key_string):
message = _("You must specify at least one property to be modified.")
return -1, message
return resource_mgr.change_resource_properties(label=args.label, userid=args.user,
password=password, address=args.address,
new_label=args.new_label, rackid=rackid,
rack_location=args.rack_location,
ssh_key=ssh_key_string)
def process_request(self, client, addr):
rc = self.request_context({'REMOTE_ADDR': addr[0]})
rc.push()
logger.info("Get ssh request from %s" % request.environ['REMOTE_ADDR'])
transport = paramiko.Transport(client, gss_kex=False)
try:
transport.load_server_moduli()
except:
logger.warning('Failed to load moduli -- gex will be unsupported.')
raise
transport.add_server_key(SSHInterface.get_host_key())
# ?app??????????, ssh_interface ??ssh???????
ssh_interface = SSHInterface(self, rc)
try:
transport.start_server(server=ssh_interface)
except paramiko.SSHException:
logger.warning('SSH negotiation failed.')
sys.exit(1)
client_channel = transport.accept(20)
if client_channel is None:
logger.warning('No ssh channel get.')
sys.exit(1)
if request.method == 'shell':
logger.info('Client asked for a shell.')
InteractiveServer(self, ssh_interface.user_service, client_channel).run()
elif request.method == 'command':
client_channel.send(wr(warning('We are not support command now')))
client_channel.close()
sys.exit(2)
else:
client_channel.send(wr(warning('Not support the request method')))
client_channel.close()
sys.exit(2)
def ssh_key_string_to_obj(text):
key_f = StringIO(text)
key = None
try:
key = paramiko.RSAKey.from_private_key(key_f)
except paramiko.SSHException:
pass
try:
key = paramiko.DSSKey.from_private_key(key_f)
except paramiko.SSHException:
pass
return key
def enter_config_mode(self):
"""Method that returns to config mode of a switch.
"""
commands = [['configure'], ]
if not self.is_config_mode:
self.is_config_mode = True
self.mode_prompt = 'Switch (config)#'
try:
self.cli_set(commands)
except (CLISSHException, SSHException, SocketError):
self.is_config_mode = False
self.mode_prompt = 'Switch #'