我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用paramiko.SSHException()。
def from_string(cls, key_string): try: pkey = paramiko.RSAKey(file_obj=StringIO(key_string)) return pkey except paramiko.SSHException: try: pkey = paramiko.DSSKey(file_obj=StringIO(key_string)) return pkey except paramiko.SSHException: return None
def loginandcopy(hostname,uname,pwd,sfile,tfile): try: log.info("Establishing ssh connection") client = getsshClient() client.load_system_host_keys() client.connect(hostname)#,username=uname)#,password=pwd) except paramiko.AuthenticationException: print("Authentication failed, please verify your credentials: %s") except paramiko.SSHException as sshException: print("Unable to establish SSH connection: %s" % sshException) except paramiko.BadHostKeyException as badHostKeyException: print("Unable to verify server's host key: %s" % badHostKeyException) except Exception as e: print(e.args) try: log.info("Getting SCP Client") scpclient = scp.SCPClient(client.get_transport()) log.info(scpclient) log.info("Hostname: %s", hostname) log.info("source file: %s", sfile) log.info("target file: %s", tfile) scpclient.put(sfile,tfile) except scp.SCPException as e: print("Operation error: %s", e)
def loginandrun(hostname,uname,pwd,command): try: log.info("Establishing ssh connection") client = getsshClient() client.load_system_host_keys() client.connect(hostname)#,username=uname)#,password=pwd) except paramiko.AuthenticationException: print("Authentication failed, please verify your credentials: %s") except paramiko.SSHException as sshException: print("Unable to establish SSH connection: %s" % sshException) except paramiko.BadHostKeyException as badHostKeyException: print("Unable to verify server's host key: %s" % badHostKeyException) try: stdin, stdout, stderr = client.exec_command(command) result = stderr.read() if len(result) > 0: print("hit error" + result) except Exception as e: print("Operation error: %s", e) # Any new implementation to use this method
def loginandcopydir(hostname,uname,pwd,sfile,tfile,recursive,preserve_times): try: log.info("Establishing ssh connection") client = getsshClient() client.load_system_host_keys() client.connect(hostname) #,username=uname)#,password=pwd) except paramiko.AuthenticationException: print("Authentication failed, please verify your credentials: %s") except paramiko.SSHException as sshException: print("Unable to establish SSH connection: %s" % sshException) except paramiko.BadHostKeyException as badHostKeyException: print("Unable to verify server's host key: %s" % badHostKeyException) except Exception as e: print(e.args) try: scpclient = scp.SCPClient(client.get_transport()) scpclient.put(sfile,tfile,recursive,preserve_times) except scp.SCPException as e: print("Operation error: %s", e) # Deprecated
def process(self): """ Process response files """ try: with self.sftp.cd(settings.EXAMS_SFTP_RESULTS_DIR): for remote_path, local_path in self.filtered_files(): try: if self.process_zip(local_path): self.sftp.remove(remote_path) log.debug("Processed remote file: %s", remote_path) except (EOFError, SSHException,): raise except: # pylint: disable=bare-except log.exception("Error processing file: %s", remote_path) finally: if os.path.exists(local_path): os.remove(local_path) except (EOFError, SSHException,) as exc: raise RetryableSFTPException("Exception processing response files") from exc
def ssh_exec_command(ssh_obj, cmd, prefix=''): """ Execute a command on the ssh connection. :param ssh_obj: SSH object. :param cmd: command to run. :param prefix: Prefix to be used for printing :return: stdout and stderr """ try: print(prefix+ "[*] Running Command:" + cmd) _, stdout_obj, stderr_obj = ssh_obj.exec_command(cmd) exit_status = stdout_obj.channel.recv_exit_status() if exit_status == 0: print(prefix + GREEN_PRINT + "[+] Command:" + cmd + " Completed Successfully" + END_PRINT) else: print(prefix + RED_PRINT + "[*] Command:" + cmd + " Return Code:" + str(exit_status) + END_PRINT) except paramiko.SSHException as e: print(prefix + RED_PRINT + "[!] Problem occurred while running command: %s, Error: %s" % (cmd, e) + END_PRINT) raise e return stdout_obj, stderr_obj
def check_device_state(self): """Attempts to connect to the shell retries number of times. Raises: Exception: device is not ready """ if not (self.switch.cli.conn.check_client() and self.switch.cli.conn.check_shell()): try: self.switch.ui.connect() except (CLISSHException, SSHException, SocketError): self.switch.ui.disconnect() raise Exception("Device is not ready.") # Add cli application check # Platform
def construct_ssh_auth_args(self, root_pw=None, pkey=None, pkey_pw=None): args = {} if root_pw: args.update({"password": root_pw}) if pkey: try: # private key to match a public key on the server # optionally encrypted pkey_filelike = StringIO(pkey) if pkey_pw: pkey_paramiko = paramiko.RSAKey.from_private_key( pkey_filelike, pkey_pw) else: pkey_paramiko = paramiko.RSAKey.from_private_key(pkey_filelike) args.update({"pkey": pkey_paramiko}) except SSHException: # Invalid key, or wrong passphase to enc key # pass on form of auth pass return args
def agent_auth(transport, username): """ Attempt to authenticate to the given transport using any of the private keys available from an SSH agent. """ agent = paramiko.Agent() agent_keys = agent.get_keys() if len(agent_keys) == 0: return for key in agent_keys: print('Trying ssh-agent key %s' % hexlify(key.get_fingerprint())) try: transport.auth_publickey(username, key) print('... success!') return except paramiko.SSHException: print('... nope.')
def ssh(config, host): """ Check that a host is running SSH :param config: Unused :param host: The host to check :return: 3-tuple of (success, name, message) success: Boolean value indicating if there is a problem or not name: DNS name message: String describing the status """ del config name = host try: ssh_conn = paramiko.SSHClient() ssh_conn.set_missing_host_key_policy( paramiko.client.MissingHostKeyPolicy()) ssh_conn.connect(host) return True except (paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException, socket.error) as e: return (False, name, "Unable to SSH to %s %s %s" % (host, e.__class__, e))
def test_7_banner_timeout(self): """ verify that the SSHClient has a configurable banner timeout. """ # Start the thread with a 1 second wait. threading.Thread(target=self._run, kwargs={'delay': 1}).start() host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key')) public_host_key = paramiko.RSAKey(data=host_key.asbytes()) self.tc = paramiko.SSHClient() self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port), 'ssh-rsa', public_host_key) # Connect with a half second banner timeout. self.assertRaises( paramiko.SSHException, self.tc.connect, self.addr, self.port, username='slowdive', password='pygmalion', banner_timeout=0.5 )
def exec_command(self, cmd, indata=None, timeout=30): logger.info("Executing command: {0}".format(cmd)) if self.transport is None or self.transport.is_active() is False: self.reconnect() if self.transport is None or self.transport.is_active() is False: logger.error("connection failed.") return -1, None input_data = self.__fix_indata(indata) try: session = self.transport.open_session() session.set_combine_stderr(True) session.get_pty() session.exec_command(cmd) except paramiko.SSHException as ex: logger.error("Exception for command '{0}: {1}'".format(cmd, ex)) session.close() return -1, None output = self.poll(session, timeout, input_data) status = session.recv_exit_status() logger.info("Returned status {0}".format(status)) session.close() return status, output
def run(self, command): """ Execute a command on the remote host. Return a tuple containing an integer status and a two strings, the first containing stdout and the second containing 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 _connect(self, ssh): if self.san_password: ssh.connect(self.san_ip, port=self.san_ssh_port, username=self.san_login, password=self.san_password, timeout=self.ssh_conn_timeout) elif self.san_privatekey: pkfile = os.path.expanduser(self.san_privatekey) privatekey = paramiko.RSAKey.from_private_key_file(pkfile) ssh.connect(self.san_ip, port=self.san_ssh_port, username=self.san_login, pkey=privatekey, timeout=self.ssh_conn_timeout) else: msg = "Specify a password or private_key" raise exceptions.SSHException(msg)
def open(self): """Opens a new SSH connection if the transport layer is missing. This can be called if an active SSH connection is open already. """ # Create a new SSH connection if the transport layer is missing. if self.ssh: transport_active = False if self.ssh.get_transport(): transport_active = self.ssh.get_transport().is_active() if not transport_active: try: self._connect(self.ssh) except Exception as e: msg = "Error connecting via ssh: %s" % e self._logger.error(msg) raise paramiko.SSHException(msg)
def was_command_successful(self, output): """ Given the entire output of an SSH command, this will check to see if the result returned is 0, aka it was successful. If result is not 0, the command failed and we return False. :param output: The output string of an SSH command :type output: str :returns: True if the command was successful """ output_string = ''.join(output) match = re.match('.*result\s+0', output_string) if not match: raise exceptions.SSHException( "The command did not execute successfully.") return True
def test_create_ssh_except(self): """Make sure that SSH exceptions are not quietly eaten.""" self.cl.setSSHOptions(ip, user, password, known_hosts_file=None, missing_key_policy=paramiko.AutoAddPolicy) self.cl.ssh.ssh = mock.Mock() self.cl.ssh.ssh.invoke_shell.side_effect = Exception('boom') cmd = ['fake'] self.assertRaises(exceptions.SSHException, self.cl.ssh._run_ssh, cmd) self.cl.ssh.ssh.assert_has_calls( [ mock.call.get_transport(), mock.call.get_transport().is_alive(), mock.call.invoke_shell(), mock.call.get_transport(), mock.call.get_transport().is_alive(), ] )
def test_was_command_successful_false(self): # Create our fake SSH client ssh_client = ssh.HPELeftHandSSHClient('foo', 'bar', 'biz') # Test invalid command output cmd_out = ['invalid'] self.assertRaises(exceptions.SSHException, ssh_client.was_command_successful, cmd_out) # Test valid command output, but command failed cmd_out = ['', 'HP StoreVirtual LeftHand OS Command Line Interface', '(C) Copyright 2007-2013', '', 'RESPONSE', ' result 8080878378'] self.assertRaises(exceptions.SSHException, ssh_client.was_command_successful, cmd_out)
def test_connect_without_password_and_private_key(self): ssh_client = ssh.HPELeftHandSSHClient(ip, user, password, known_hosts_file=None, missing_key_policy=paramiko. AutoAddPolicy) mock_expand_user = mock.Mock() mock_expand_user.return_value = 'my_user' mock_from_private_key_file = mock.Mock() mock_from_private_key_file.return_value = 'my_private_key' ssh_client.san_password = None ssh_client.san_privatekey = None ssh_client.ssh = mock.Mock() ssh_client.ssh.get_transport.return_value = False self.assertRaises(paramiko.SSHException, ssh_client.open)
def test_run_ssh_with_exception(self): ssh_client = ssh.HPELeftHandSSHClient(ip, user, password, known_hosts_file=None, missing_key_policy=paramiko. AutoAddPolicy) ssh_client.check_ssh_injection = mock.Mock() ssh_client.check_ssh_injection.return_value = True ssh_client._ssh_execute = mock.Mock() ssh_client._ssh_execute.side_effect = Exception('End this here') ssh_client._create_ssh = mock.Mock() ssh_client._create_ssh.return_value = True ssh_client.ssh = mock.Mock() ssh_client.ssh.get_transport.is_alive.return_value = True command = ['fake'] self.assertRaises(exceptions.SSHException, ssh_client._run_ssh, command, attempts=1) ssh_client.check_ssh_injection.assert_called_once() ssh_client._ssh_execute.assert_called_once() ssh_client._create_ssh.assert_not_called()
def SSHConnect(host, user, passwd, port): ssh = paramiko.SSHClient() try: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # any remote (~/.ssh/known_hosts) ssh.connect(host, port = int(port), username = user, password = passwd, allow_agent=False, look_for_keys=False) except: #except paramiko.SSHException: ssh.close() ssh = None print('error> failed to connect', host, '(please check your input: ip, port, user, password)') return ssh
def connect(self): """Connect to host """ try: self.client.connect(self.host, username=self.username, password=self.password, port=self.port, pkey=self.pkey, timeout=self.timeout) except paramiko.AuthenticationException as e: raise DaskEc2Exception("Authentication Error to host '%s'" % self.host) except sock_gaierror as e: raise DaskEc2Exception("Unknown host '%s'" % self.host) except sock_error as e: raise DaskEc2Exception("Error connecting to host '%s:%s'\n%s" % (self.host, self.port, e)) except paramiko.SSHException as e: raise DaskEc2Exception("General SSH error - %s" % e)
def _initialize_ssh_connection(self): LOG.debug("Connecting to the VM via SSH") self.ssh = paramiko.client.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.client.AutoAddPolicy()) try: self.ssh.connect("127.0.0.1", port=self._ssh_port, username=self._ssh_username, key_filename=self._ssh_keyfile, timeout=self._ssh_timeout) # Set TCP Keep-Alive to 5 seconds, so that the connection does not die transport = self.ssh.get_transport() transport.set_keepalive(5) # also raises BadHostKeyException, should be taken care of via AutoAddPolicy() # also raises AuthenticationException, should never occur because keys are provisioned except socket.error as e: LOG.error("TCP error connecting to SSH on VM.") raise e except paramiko.SSHException as e: LOG.error("SSH error trying to connect to VM.") raise e
def execute(self, command): assert self.ssh is not None environment = " ".join("{}='{}'".format(k, v) for k, v in os.environ.items() if k.startswith("POSTGRES")) env_command = "{} {}".format(environment, command) LOG.debug("Executing command: %s", env_command) stdout_content = None stderr_content = None try: _, stdout, stderr = self.ssh.exec_command(env_command) exit_status = stdout.channel.recv_exit_status() if exit_status != 0: raise paramiko.SSHException("'%s' failed with exit status %d", command, exit_status) stdout_content = stdout.read() stderr_content = stderr.read() except paramiko.SSHException as e: LOG.error("Unable to excute command '%s' on host: %s", command, e) LOG.debug("stdout: %s", stdout.read()) LOG.debug("stderr: %s", stderr.read()) raise e return stdout_content, stderr_content
def trySSHConnect(self,host, portNum): paramiko.util.log_to_file ('paramiko.log') try: self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(host,port=portNum,username="pi", password="raspberry") self.ssh.get_transport().window_size = 3 * 1024 * 1024 command='python /home/pi/Desktop/control_gpio_pi/initial_check.py' stdin,stdout,stderr = self.ssh.exec_command(command) print('\nstout:',stdout.read()) except paramiko.AuthenticationException: print ("Authentication failed!") return -1 except paramiko.BadHostKeyException: print ("BadHostKey Exception!") return -1 except paramiko.SSHException: print ("SSH Exception!") self.ssh.close() return -1 except socket.error as e: print ("Socket error ", e) return -1 except: print ("Could not SSH to %s, unhandled exception" % host) return -1 print ("Made connection to " + host + ":" + str(portNum)) return 0
def get_connection(): """ Creates a new SFTP connection Returns: connection(pysftp.Connection): the configured connection """ missing_settings = [] for key in PEARSON_UPLOAD_REQUIRED_SETTINGS: if getattr(settings, key) is None: missing_settings.append(key) if missing_settings: raise ImproperlyConfigured( "The setting(s) {} are required".format(', '.join(missing_settings)) ) cnopts = pysftp.CnOpts() cnopts.hostkeys = None # ignore knownhosts try: return pysftp.Connection( host=str(settings.EXAMS_SFTP_HOST), port=int(settings.EXAMS_SFTP_PORT), username=str(settings.EXAMS_SFTP_USERNAME), password=str(settings.EXAMS_SFTP_PASSWORD), cnopts=cnopts, ) except (ConnectionException, SSHException) as ex: raise RetryableSFTPException() from ex
def upload_tsv(file_path): """ Upload the given TSV files to the remote Args: file_path (str): absolute path to the file to be uploaded """ try: with get_connection() as sftp: with sftp.cd(settings.EXAMS_SFTP_UPLOAD_DIR): sftp.put(file_path) except (EOFError, SSHException,) as exc: raise RetryableSFTPException() from exc
def test_process_ssh_exception_cd( self, process_zip_mock, filtered_files_mock, os_path_exists_mock, os_remove_mock): """Test that SSH exceptions bubble up""" self.sftp.cd.side_effect = SSHException('exception') processor = download.ArchivedResponseProcessor(self.sftp) with self.assertRaises(RetryableSFTPException): processor.process() filtered_files_mock.assert_not_called() self.sftp.remove.assert_not_called() process_zip_mock.assert_not_called() os_path_exists_mock.assert_not_called() os_remove_mock.assert_not_called()
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
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 #'