def from_line(cls, line, lineno=None, filename=None): ''' Parses the given line of text to find the name(s) for the host, the type of key, and the key data. ''' if not line or not line.strip(): return None fields = line.strip().split(' ') if not fields or fields[0].startswith('#'): return None if fields[0].startswith('@'): marker = fields[0] fields = fields[1:] else: marker = None if len(fields) < 3: raise UnreadableKey('Invalid known_hosts line', line, lineno) names, keytype, key = fields[:3] names = names.split(',') # Decide what kind of key we're looking at and create an object # to hold it accordingly. key = key.encode('ascii') # SSH-2 Key format consists of 2 (text) fields # keytype, base64_blob try: if keytype == 'ssh-rsa': key = paramiko.RSAKey(data=base64.b64decode(key)) elif keytype == 'ssh-dss': key = paramiko.DSSKey(data=base64.b64decode(key)) elif keytype == 'ecdsa-sha2-nistp256': key = paramiko.ECDSAKey(data=base64.b64decode(key), validate_point=False) elif len(fields) > 3: # SSH-1 Key format consists of 3 integer fields # bits, exponent, modulus (RSA Only) try: bits = int(fields[1]) exponent = int(fields[2]) modulus = long(fields[3]) key = paramiko.RSAKey(vals=(exponent, modulus)) except ValueError: raise UnreadableKey('Invalid known_hosts line', line, lineno, filename) else: raise UnreadableKey('Invalid known_hosts line', line, lineno, filename) return cls(names, key, marker, lineno, filename) except Exception as e: raise UnreadableKey('Invalid known_hosts line (%s)' % e, line, lineno, filename)
def _cinfo(self): cnopts = pysftp.CnOpts() key = paramiko.ECDSAKey(data=base64.decodebytes(HOSTKEY[2])) cnopts.hostkeys.add(HOSTKEY[0], HOSTKEY[1], key) # https://github.com/paramiko/paramiko/issues/1015 private_key = self.private_key.replace( b"-----BEGIN PRIVATE KEY-----", b"-----BEGIN RSA PRIVATE KEY-----").replace( b"-----END PRIVATE KEY-----", b"-----END RSA PRIVATE KEY-----") return { "host": self.hostname, "username": self.sftp_user, "port": int(self.sftp_port), "private_key": paramiko.RSAKey(file_obj=StringIO(private_key.decode())), "cnopts": cnopts, }
def main(sock, dport, logger, config, **kwargs): ssh_config = munchify({'shell': config.get('shell', {}), **config.protocols.ssh}) transport = paramiko.Transport(sock) transport.local_version = 'SSH-2.0-%s' % ssh_config.get('banner', 'OpenSSH-7.8p1') for key, value in ssh_config.key.items(): if key == 'dsa': transport.add_server_key(paramiko.DSSKey(filename=value)) elif key == 'rsa': transport.add_server_key(paramiko.RSAKey(filename=value)) elif key == 'ecdsa': transport.add_server_key(paramiko.ECDSAKey(filename=value)) elif key == 'ed25519': transport.add_server_key(paramiko.Ed25519Key(filename=value)) server = Server(dport, transport, logger, ssh_config) transport.start_server(server=server) transport.join()
def generate_fingerprint(public_key): try: parts = public_key.split(' ') ssh_alg = parts[0] pub_data = parts[1].decode('base64') if ssh_alg == 'ssh-rsa': pkey = paramiko.RSAKey(data=pub_data) elif ssh_alg == 'ssh-dss': pkey = paramiko.DSSKey(data=pub_data) elif ssh_alg == 'ecdsa-sha2-nistp256': pkey = paramiko.ECDSAKey(data=pub_data, validate_point=False) else: raise exception.InvalidKeypair( reason=_('Unknown ssh key type %s') % ssh_alg) raw_fp = binascii.hexlify(pkey.get_fingerprint()) return ':'.join(a + b for a, b in zip(raw_fp[::2], raw_fp[1::2])) except (IndexError, UnicodeDecodeError, binascii.Error, paramiko.ssh_exception.SSHException): raise exception.InvalidKeypair( reason=_('failed to generate fingerprint'))
def _connect(self): """Connect to the SSH server.""" from paramiko import ECDSAKey, SSHClient, ssh_exception from base64 import b64decode try: key = paramiko.ECDSAKey(data=base64.b64decode(self._key)) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.get_host_keys().add(self._host, 'ssh-rsa', key) if self._password is not None: _LOGGER.info("Using password as credential") client.connect(self._host, username=self._username, password=self._password) elif self._keyfile is not None: _LOGGER.info("Using keyfile as credential") client.connect(self._host, username=self._username, key_filename=self._keyfile, passphrase="") else: _LOGGER.error("No explicit client credential given") client.connect(self._host, username=self._username) self._ssh = client self._connected = True except ssh_exception.BadHostKeyException as err: _LOGGER.error("Host Key Mismatch: %s", str(err)) self._disconnect() return None except: import traceback _LOGGER.error("Connection refused. SSH enabled? %s", traceback.format_exc()) self._disconnect()
import paramiko import base64 from pyunifi.controller import Controller import time from config import * add = 1 remove = -1 ssh = paramiko.SSHClient() key = paramiko.ECDSAKey(data=base64.b64decode(cisco_ECDSAKey)) ssh.get_host_keys().add(cisco_ip, "ecdsa-sha2-nistp256", key) def modify_unifi(macs, action): c = Controller(unifi_controller_url, unifi_username, unifi_password, port=unifi_port) wlans = c.get_wlan_conf() for wlan in wlans: if wlan["name"] == wlan_name and wlan["_id"] == wlan_id: macFilterList = wlan["mac_filter_list"] for mac in macs: if (action == add): if mac not in macFilterList: macFilterList.append(mac.upper()) elif (action == remove): if mac in macFilterList: macFilterList.remove(mac.upper()) newSetting = {"mac_filter_list": macFilterList} c._api_update("rest/wlanconf/{0}".format(wlan_id), newSetting) break def modify_cisco(macs, action): ssh.connect(cisco_ip, username="******", password="******") # these creds don't matter, cuz cisco ¯\_(ツ)_/¯
def _importKey(filename, allow_prompt=True, logger=None): ''' Import a RSA or DSA key from file contents If the key file requires a passphrase, ask for it only if allow_prompt is True. Otherwise, reraise the paramiko.PasswordRequiredException. If the key fails to load as a RSA key, try loading as DSA key. If it fails both, then raises a ValueError with the reported errors from both RSA and DSA attempts. ''' # Try RSA first try: key = paramiko.RSAKey(filename=filename) if logger: logger.debug('Loaded unprotected RSA key from %s', filename) return key except paramiko.PasswordRequiredException: # Need passphrase for RSA key if not allow_prompt: return RuntimeError('RSA Key is Passphrase-Protected') retries = 3 while retries: try: passphrase = user_password( 'Enter passphrase for RSA key [%s]: ' % filename) key = paramiko.RSAKey(filename=filename, password=passphrase) if logger: logger.debug('Loaded passphrase protected RSA key from %s', filename) return key except paramiko.SSHException as e: print(repr(e)) retries -= 1 return Exception('3 failed passphrase attempts for %s' % filename) except paramiko.SSHException as e: rsa_exception = e if logger: logger.debug('Failed to load %s as RSA key\n\t%s', filename, repr(rsa_exception)) # Format error - could be ECDSA key instead... try: key = paramiko.ECDSAKey(filename=filename) if logger: logger.debug('Loaded unprotected ECDSA key from %s', filename) return key except paramiko.PasswordRequiredException: # Need passphrase for ECDSA key if not allow_prompt: return RuntimeError('ECDSA Key is Passphrase-Protected') retries = 3 while retries: try: passphrase = user_password( 'Enter passphrase for ECDSA key [%s]: ' % filename) key = paramiko.ECDSAKey(filename=filename, password=passphrase) if logger: logger.debug( 'Loaded passphrase protected ECDSA key from %s', filename) return key except paramiko.SSHException as e: print(repr(e)) retries -= 1 return Exception('3 failed passphrase attempts for %s' % filename) except paramiko.SSHException as e: ecdsa_exception = e if logger: logger.debug('Failed to load %s as ECDSA key\n\t%s', filename, repr(ecdsa_exception)) # Format error - could be DSA key instead... try: key = paramiko.DSSKey(filename=filename) if logger: logger.debug('Loaded unprotected DSA key from %s', filename) return key except paramiko.PasswordRequiredException: # Need passphrase for DSA key if not allow_prompt: return RuntimeError('DSA Key is Passphrase-Protected') retries = 3 while retries: try: passphrase = user_password( 'Enter passphrase for DSA key [%s]: ' % filename) key = paramiko.DSSKey(filename=filename, password=passphrase) if logger: logger.debug('Loaded passphrase protected DSA key from %s', filename) return key except paramiko.SSHException as e: print(repr(e)) retries -= 1 return Exception('3 failed passphrase attempts for %s' % filename) except paramiko.SSHException as e: dsa_exception = e if logger: logger.debug('Failed to load %s as DSA key\n\t%s', filename, repr(dsa_exception)) # Give up on using this key if logger: logger.error( 'Unable to load key from [%s] | RSA failure: %r | ECDSA failure: %r | DSA failure: %r' % (filename, rsa_exception, ecdsa_exception, dsa_exception)) # Return, rather than raise the exception - Caller just needs something to # fill the deferred_keys entry with that's not a paramiko.PKey and not None. return RuntimeError('Unrecognized key: %s' % filename)
print "beg" ipaddr = "134.141.50.33" usernm = "susingha" passwd = "aerohive" import base64 import paramiko # the base64 is the host key of the ssh server as found in the known hosts file of the client key = paramiko.ECDSAKey(data=base64.b64decode( b'AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBD7CedKyt5CqadgHv6CyfiNBeRY5suIz7smsrI93caNY/ciCOlrWrGT3o4KDHrVhg3YiiptloE8OXbfb1J9DcvM=' )) #ey = paramiko.RSAKey(data=base64.b64decode(b'AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBD7CedKyt5CqadgHv6CyfiNBeRY5suIz7smsrI93caNY/ciCOlrWrGT3o4KDHrVhg3YiiptloE8OXbfb1J9DcvM=')) client = paramiko.SSHClient() client.get_host_keys().add(ipaddr, 'ecdsa-sha2-nistp256', key) #lient.get_host_keys().add(ipaddr, 'ssh-rsa', key) client.connect(ipaddr, username=usernm, password=passwd) stdin, stdout, stderr = client.exec_command('sudo ls -l') for line in stdout: print(line.strip('\n')) for line in stderr: print(line.strip('\n')) stdin, stdout, stderr = client.exec_command('aerohive') for line in stdout: print(line.strip('\n')) for line in stdout: print(line.strip('\n'))