Python paramiko.SSHException() Examples
The following are 30
code examples of paramiko.SSHException().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
paramiko
, or try the search function
.
Example #1
Source File: RemoteCrashFetcher.py From LuckyCAT with GNU General Public License v3.0 | 11 votes |
def fetch_remote_crashes(self): """ some exception handling code is taken from https://www.programcreek.com/python/example/105570/scp.SCPClient """ try: ssh = SSHClient() ssh.load_system_host_keys() ssh.connect(hostname=config.remote_system_ip) self.copy_crashes_dir_with_scp(ssh) except AuthenticationException: print("Authentication failed, please verify your credentials: %s") except SSHException as sshException: print("Unable to establish SSH connection: %s" % sshException) except BadHostKeyException as badHostKeyException: print("Unable to verify server's host key: %s" % badHostKeyException) finally: ssh.close()
Example #2
Source File: installInsightAgent.py From InsightAgent with Apache License 2.0 | 9 votes |
def sshInstall(retry,hostname): global user global password global userInsightfinder global licenseKey global samplingInterval global reportingInterval global agentType if retry == 0: print "Install Fail in", hostname q.task_done() return print "Start installing agent in", hostname, "..." try: s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if os.path.isfile(password) == True: s.connect(hostname, username=user, key_filename = password, timeout=60) else: s.connect(hostname, username=user, password = password, timeout=60) transport = s.get_transport() session = transport.open_session() session.set_combine_stderr(True) session.get_pty() session.exec_command("sudo rm -rf insightagent* InsightAgent* \n \ wget --no-check-certificate https://github.com/insightfinder/InsightAgent/archive/master.tar.gz -O insightagent.tar.gz && \ tar xzvf insightagent.tar.gz && \ cd InsightAgent-master && deployment/checkpackages.sh -env\n") stdin = session.makefile('wb', -1) stdout = session.makefile('rb', -1) stdin.write(password+'\n') stdin.flush() session.recv_exit_status() #wait for exec_command to finish s.close() print "Install Succeed in", hostname q.task_done() return except paramiko.SSHException, e: print "Invalid Username/Password for %s:"%hostname , e return sshInstall(retry-1,hostname)
Example #3
Source File: network.py From LiMEaide with GNU General Public License v3.0 | 9 votes |
def connect(self): """Call to set connection with remote client.""" try: self.paramiko_session = paramiko.SSHClient() self.paramiko_session.set_missing_host_key_policy( paramiko.AutoAddPolicy()) self.paramiko_session.connect( self.client.ip, username=self.client.user, password=self.client.pass_, key_filename=self.client.key, allow_agent=True, compress=self.client.compress) except (paramiko.AuthenticationException, paramiko.ssh_exception.NoValidConnectionsError) as e: self.logger.error(e) sys.exit(colored("> {}".format(e), 'red')) except paramiko.SSHException as e: self.logger.error(e) sys.exit(colored("> {}".format(e), 'red')) self.transfer = network.Network( self.paramiko_session, self.client.ip, self.client.port) self.transfer.open()
Example #4
Source File: ShellScriptHandler.py From simoorg with Apache License 2.0 | 6 votes |
def execute_command(self, script, arguments): """ Execute the command specified in the arguments Args: script - The script to be executed arguments - arguments to the script Return: status - command_output and error_messages Raise: paramiko.SSHException - if remote command exception failed """ command = script + ' ' + self.comma_separate_args(arguments) try: (stdin, stdout, stderr) = self.ssh_client.exec_command( command, bufsize=-1, timeout=self.command_timeout) except paramiko.SSHException, exc: print "Server failed to execute command", exc raise
Example #5
Source File: stopcron.py From InsightAgent with Apache License 2.0 | 6 votes |
def sshStopCron(retry,hostname): global user global password if retry == 0: print "Stop Cron Failed in", hostname q.task_done() return try: s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if os.path.isfile(password) == True: s.connect(hostname, username=user, key_filename = password, timeout=60) else: s.connect(hostname, username=user, password = password, timeout=60) transport = s.get_transport() session = transport.open_session() session.set_combine_stderr(True) session.get_pty() command = "sudo mv /etc/cron.d/ifagent InsightAgent-master/ifagent."+time.strftime("%Y%m%d%H%M%S")+"\n" session.exec_command(command) stdin = session.makefile('wb', -1) stdout = session.makefile('rb', -1) stdin.write(password+'\n') stdin.flush() session.recv_exit_status() #wait for exec_command to finish s.close() print "Stopped Cron in ", hostname q.task_done() return except paramiko.SSHException, e: print "Invalid Username/Password for %s:"%hostname , e return sshStopCron(retry-1,hostname)
Example #6
Source File: handler.py From adminset with GNU General Public License v2.0 | 6 votes |
def post(self): if self.debug and self.get_argument('error', u''): # for testing purpose only raise ValueError('Uncaught exception') self.src_addr = self.get_client_addr() if len(clients.get(self.src_addr[0], {})) >= options.maxconn: raise tornado.web.HTTPError(403, 'Too many connections.') future = Future() t = threading.Thread(target=self.ssh_connect_wrapped, args=(future,)) t.setDaemon(True) t.start() try: worker = yield future except (ValueError, paramiko.SSHException) as exc: self.result.update(status=str(exc)) else: workers = clients.setdefault(worker.src_addr[0], {}) workers[worker.id] = worker self.loop.call_later(DELAY, recycle_worker, worker) self.result.update(id=worker.id, encoding=worker.encoding) self.write(self.result)
Example #7
Source File: paramiko_helper.py From galaxia with Apache License 2.0 | 6 votes |
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)
Example #8
Source File: SSH.py From im with GNU General Public License v3.0 | 6 votes |
def test_connectivity(self, time_out=None): """ Tests if the SSH is active Arguments: - time_out: Timeout to connect. Returns: True if the connection is established or False otherwise Raises: Exception """ try: client, proxy = self.connect(time_out) client.close() if proxy: proxy.close() return True except paramiko.AuthenticationException: raise AuthenticationException("Authentication Error!!") except paramiko.SSHException as e: if str(e) == "No authentication methods available": raise AuthenticationException("Authentication Error!!") return False except Exception: return False
Example #9
Source File: cmd_executer.py From tacker with Apache License 2.0 | 6 votes |
def execute_command(self, cmd, input_data=None): try: stdin, stdout, stderr = self.__ssh.exec_command(cmd) if input_data: stdin.write(input_data) LOG.debug("Input data written successfully") stdin.flush() LOG.debug("Input data flushed") stdin.channel.shutdown_write() # NOTE (dkushwaha): There might be a case, when server can take # too long time to write data in stdout buffer or sometimes hang # itself, in that case readlines() will stuck for long/infinite # time. To handle such cases, timeout logic should be introduce # here. cmd_out = stdout.readlines() cmd_err = stderr.readlines() return_code = stdout.channel.recv_exit_status() except paramiko.SSHException: LOG.error("Command execution failed at %s. Giving up", self.__host) raise result = CommandResult(cmd, cmd_out, cmd_err, return_code) LOG.debug("Remote command execution result: %s", result) return result
Example #10
Source File: handler.py From adminset with GNU General Public License v2.0 | 6 votes |
def on_message(self, message): logging.debug('{!r} from {}:{}'.format(message, *self.src_addr)) worker = self.worker_ref() try: msg = json.loads(message) except JSONDecodeError: return if not isinstance(msg, dict): return resize = msg.get('resize') if resize and len(resize) == 2: try: worker.chan.resize_pty(*resize) except (TypeError, struct.error, paramiko.SSHException): pass data = msg.get('data') if data and isinstance(data, UnicodeType): worker.data_to_dst.append(data) worker.on_write()
Example #11
Source File: paramiko_helper.py From galaxia with Apache License 2.0 | 6 votes |
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
Example #12
Source File: iotools.py From cgat-core with MIT License | 6 votes |
def remote_file_exists(filename, hostname=None, expect=False): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(hostname, username=getpass.getuser()) except paramiko.SSHException as ex: # disable test on VM, key issues. return expect except TimeoutError as ex: # times out on OS X, localhost return expect stdin, stdout, ssh_stderr = ssh.exec_command("ls -d {}".format(filename)) out = stdout.read().decode("utf-8") return out.strip() == filename
Example #13
Source File: paramiko_helper.py From galaxia with Apache License 2.0 | 6 votes |
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
Example #14
Source File: esxi_contrailvm.py From contrail-server-manager with Apache License 2.0 | 6 votes |
def _install_contrailvm_pkg(self, ip, user, passwd, domain, server , pkg, smgr_ip): MAX_RETRIES = 5 retries = 0 connected = False while retries <= MAX_RETRIES and connected == False: try: connected = True ssh_session = paramiko.SSHClient() ssh_session.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_session.connect(ip, username=user, password=passwd, timeout=300) sftp = ssh_session.open_sftp() except socket.error, paramiko.SSHException: connected = False ssh_session.close() _smgr_log.log(_smgr_log.DEBUG, ("Connection to %s failed, Retry: %s" % (ip, retries))) retries = retries + 1 continue
Example #15
Source File: handler.py From webssh with MIT License | 6 votes |
def get_specific_pkey(self, name, offset, password): self.iostr.seek(offset) logging.debug('Reset offset to {}.'.format(offset)) logging.debug('Try parsing it as {} type key'.format(name)) pkeycls = getattr(paramiko, name+'Key') pkey = None try: pkey = pkeycls.from_private_key(self.iostr, password=password) except paramiko.PasswordRequiredException: raise InvalidValueError('Need a passphrase to decrypt the key.') except (paramiko.SSHException, ValueError) as exc: self.last_exception = exc logging.debug(str(exc)) return pkey
Example #16
Source File: brutal_SSH.py From Brutal_SSH with MIT License | 6 votes |
def do_ssh(self, username): while not self.passwords.empty(): time.sleep(0.1) password = self.passwords.get() ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(self.host_ip, port=self.host_port, username=username, password=password, timeout=self.timeout) print info_out + ffb + "{} : {:.<50} {}".format(username, password, fgb + "Successful" + sf) ssh.close(); exit(0) except paramiko.AuthenticationException: print ver_out + ffb + "{} : {:.<50} {}".format(username, password, frb + "Failed" + sf) except socket.error, e: print err_out + ffb + "{} : {:.<50} {}".format(username, password, fcb + "Connection Failed" + sf) except paramiko.SSHException: print err_out + ffb + "{} : {:.<50} {}".format(username, password, fbb + "Error" + sf)
Example #17
Source File: utils.py From restatic with GNU General Public License v3.0 | 6 votes |
def get_private_keys(): """Find SSH keys in standard folder.""" key_formats = [RSAKey, ECDSAKey, Ed25519Key] ssh_folder = os.path.expanduser("~/.ssh") available_private_keys = [] if os.path.isdir(ssh_folder): for key in os.listdir(ssh_folder): for key_format in key_formats: try: parsed_key = key_format.from_private_key_file( os.path.join(ssh_folder, key) ) key_details = { "filename": key, "format": parsed_key.get_name(), "bits": parsed_key.get_bits(), "fingerprint": parsed_key.get_fingerprint().hex(), } available_private_keys.append(key_details) except (SSHException, UnicodeDecodeError, IsADirectoryError): continue return available_private_keys
Example #18
Source File: connection.py From conn with GNU General Public License v2.0 | 6 votes |
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.')
Example #19
Source File: remote_shell.py From margaritashotgun with MIT License | 6 votes |
def execute(self, command): """ Executes command on remote hosts :type command: str :param command: command to be run on remote host """ try: if self.ssh.get_transport() is not None: logger.debug('{0}: executing "{1}"'.format(self.target_address, command)) stdin, stdout, stderr = self.ssh.exec_command(command) return dict(zip(['stdin', 'stdout', 'stderr'], [stdin, stdout, stderr])) else: raise SSHConnectionError(self.target_address, "ssh transport is closed") except (AuthenticationException, SSHException, ChannelException, SocketError) as ex: logger.critical(("{0} execution failed on {1} with exception:" "{2}".format(command, self.target_address, ex))) raise SSHCommandError(self.target_address, command, ex)
Example #20
Source File: remote_shell.py From margaritashotgun with MIT License | 6 votes |
def execute_async(self, command, callback=None): """ Executes command on remote hosts without blocking :type command: str :param command: command to be run on remote host :type callback: function :param callback: function to call when execution completes """ try: logger.debug(('{0}: execute async "{1}"' 'with callback {2}'.format(self.target_address, command, callback))) future = self.executor.submit(self.execute, command) if callback is not None: future.add_done_callback(callback) return future except (AuthenticationException, SSHException, ChannelException, SocketError) as ex: logger.critical(("{0} execution failed on {1} with exception:" "{2}".format(command, self.target_address, ex))) raise SSHCommandError(self.target_address, command, ex)
Example #21
Source File: remote_shell.py From margaritashotgun with MIT License | 6 votes |
def upload_file(self, local_path, remote_path): """ Upload a file from the local filesystem to the remote host :type local_path: str :param local_path: path of local file to upload :type remote_path: str :param remote_path: destination path of upload on remote host """ logger.debug("{0}: uploading {1} to {0}:{2}".format(self.target_address, local_path, remote_path)) try: sftp = paramiko.SFTPClient.from_transport(self.transport()) sftp.put(local_path, remote_path) sftp.close() except SSHException as ex: logger.warn(("{0}: LiME module upload failed with exception:" "{1}".format(self.target_address, ex)))
Example #22
Source File: vm_setup.py From setup with BSD 2-Clause "Simplified" License | 6 votes |
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
Example #23
Source File: handler.py From webssh with MIT License | 6 votes |
def on_message(self, message): logging.debug('{!r} from {}:{}'.format(message, *self.src_addr)) worker = self.worker_ref() try: msg = json.loads(message) except JSONDecodeError: return if not isinstance(msg, dict): return resize = msg.get('resize') if resize and len(resize) == 2: try: worker.chan.resize_pty(*resize) except (TypeError, struct.error, paramiko.SSHException): pass data = msg.get('data') if data and isinstance(data, UnicodeType): worker.data_to_dst.append(data) worker.on_write()
Example #24
Source File: libsshscan.py From libssh-scanner with MIT License | 6 votes |
def aggressive(ip, port, banner): # bypass auth to verify vulnerable host try: s = socket.create_connection((ip, port), timeout=0.50000) s.settimeout(None) msg = paramiko.message.Message() t = paramiko.transport.Transport(s) t.start_client() msg.add_byte(paramiko.common.cMSG_USERAUTH_SUCCESS) t._send_message(msg) c = t.open_session(timeout=0.50000) s.close() pvulnerable(ip, port, banner) except (socket.timeout, socket.error) as e: ptimeout(ip, port) except paramiko.SSHException as e: pstatus(ip, port, banner) #print e except Exception as e: pexception(ip, port, banner)
Example #25
Source File: cli_helper.py From manila with Apache License 2.0 | 6 votes |
def __call__(self, cmd_list, check_exit_code=True, attempts=1): """SSH tool""" manila_utils.check_ssh_injection(cmd_list) command = ' '.join(cmd_list) if not self.sshpool: try: self.sshpool = manila_utils.SSHPool( self.host, self.port, self.ssh_conn_timeout, self.login, password=self.password, privatekey=self.privatekey, min_size=self.ssh_min_pool_size, max_size=self.ssh_max_pool_size ) except paramiko.SSHException: LOG.error("Unable to create SSHPool") raise try: return self._ssh_execute(self.sshpool, command, check_exit_code, attempts) except Exception: LOG.error("Error running SSH command: %s", command) raise
Example #26
Source File: handler.py From webssh with MIT License | 6 votes |
def get_default_encoding(self, ssh): commands = [ '$SHELL -ilc "locale charmap"', '$SHELL -ic "locale charmap"' ] for command in commands: try: _, stdout, _ = ssh.exec_command(command, get_pty=True) except paramiko.SSHException as exc: logging.info(str(exc)) else: data = stdout.read() logging.debug('{!r} => {!r}'.format(command, data)) result = self.parse_encoding(data) if result: return result logging.warning('Could not detect the default encoding.') return 'utf-8'
Example #27
Source File: test_netmiko_base.py From networking-generic-switch with Apache License 2.0 | 5 votes |
def test__get_connection_timeout(self, m_conn_handler, m_stop, m_wait): switch = self._make_switch_device({'ngs_ssh_connect_timeout': '1', 'ngs_ssh_connect_interval': '1'}) m_conn_handler.side_effect = ( paramiko.SSHException) def get_connection(): with switch._get_connection(): self.fail() self.assertRaises(exc.GenericSwitchNetmikoConnectError, get_connection) m_stop.assert_called_once_with(1) m_wait.assert_called_once_with(1)
Example #28
Source File: sshkey.py From DevOps with GNU General Public License v2.0 | 5 votes |
def ssh_private_key2obj(ssh_key): key = None try: key = paramiko.RSAKey.from_private_key(StringIO(ssh_key)) except paramiko.SSHException: pass return key
Example #29
Source File: patator_ext.py From project-black with GNU General Public License v2.0 | 5 votes |
def load_keyfile(keyfile): for cls in (paramiko.RSAKey, paramiko.DSSKey, paramiko.ECDSAKey): try: return cls.from_private_key_file(keyfile) except paramiko.SSHException: pass else: raise
Example #30
Source File: ssh.py From stash with MIT License | 5 votes |
def connect(self, host, passwd=None, port=22): print('Connecting...') if "@" in host: username, host = host.split('@') else: # TODO: find better default username username = "root" if passwd is not None: return self._connect_with_passwd(host, username, passwd, port) else: print('Looking for SSH keys...') key_filename = self.find_ssh_keys() if len(key_filename) > 0: try: self.client.connect(host, username=username, password=passwd, port=port, key_filename=key_filename) return True except paramiko.SSHException as e: print('Failed to login with SSH Keys: {}'.format(repr(e))) print('Trying password ...') passwd = input('Enter password:') return self._connect_with_passwd(host, username, passwd, port) except Exception as e: print('Error: {}'.format(e)) return False else: print('No SSH key found. Trying password ...') passwd = input('Enter password:') return self._connect_with_passwd(host, username, passwd, port)