Exemple #1
0
    def __init__(self, **kwargs):
        Protocol.__init__(self, **kwargs)
        self.client = None
        self.shell = None
        self.cancel = False

        # Since each protocol may be created in it's own thread, we must
        # re-initialize the random number generator to make sure that
        # child threads have no way of guessing the numbers of the parent.
        # If we don't, PyCrypto generates an error message for security
        # reasons.
        try:
            Crypto.Random.atfork()
        except AttributeError:
            # pycrypto versions that have no "Random" module also do not
            # detect the missing atfork() call, so they do not raise.
            pass

        # Paramiko client stuff.
        self._system_host_keys = paramiko.HostKeys()
        self._host_keys = paramiko.HostKeys()
        self._host_keys_filename = None

        if self.verify_fingerprint:
            self._missing_host_key = self._reject_host_key
        else:
            self._missing_host_key = self._add_host_key
Exemple #2
0
 def test_save(self):
     hostdict = paramiko.HostKeys('hostfile.temp')
     self.assertEqual(2,len(hostdict))
     hh = '|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c='
     key = paramiko.RSAKey(data=decodebytes(keyblob))
     hostdict.add(hh, 'ssh-rsa', key)
     hostdict.save('hostfile.temp')
     hostdict2 = paramiko.HostKeys('hostfile.temp')
     self.assertEqual(3,len(hostdict2))
     x = hostdict['foo.example.com']
     fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper()
     self.assertEqual(b'7EC91BB336CB6D810B124B1353C32396', fp)
Exemple #3
0
    def test_5_dict(self):
        hostdict = paramiko.HostKeys('hostfile.temp')
        self.assertTrue('secure.example.com' in hostdict)
        self.assertTrue(hostdict.clear_host('secure.example.com'))
        self.assertTrue('secure.example.com' not in hostdict)
        self.assertFalse(hostdict.clear_host('secure.example.com'))

        hostdict = paramiko.HostKeys('hostfile.temp')
        self.assertTrue('secure.example.com' in hostdict)
        hostdict.clear_host('secure.example.com')
        hostdict.save('hostfile.temp')
        hostdict.load('hostfile.temp')
        self.assertTrue('secure.example.com' not in hostdict)
Exemple #4
0
    def test_1_load(self):
        try:
            badhost = paramiko.HostKeys('badfile.temp')
        except IOError:
            pass
        else:
            assert False, "Attempted to open a file which does not exist"

        hostdict = paramiko.HostKeys('hostfile.temp')
        self.assertEqual(2, len(hostdict))
        self.assertEqual(1, len(list(hostdict.values())[0]))
        self.assertEqual(1, len(list(hostdict.values())[1]))
        fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper()
        self.assertEqual(b'E6684DB30E109B67B70FF1DC5C7F1363', fp)
 def test_1_load(self):
     hostdict = paramiko.HostKeys('hostfile.temp')
     self.assertEqual(2, len(hostdict))
     self.assertEqual(1, len(list(hostdict.values())[0]))
     self.assertEqual(1, len(list(hostdict.values())[1]))
     fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper()
     self.assertEqual(b'E6684DB30E109B67B70FF1DC5C7F1363', fp)
Exemple #6
0
    def __init__(self, device_handler):
        capabilities = Capabilities(device_handler.get_capabilities())
        Session.__init__(self, capabilities)
        self._host = None
        self._host_keys = paramiko.HostKeys()
        self._transport = None
        self._connected = False
        self._channel = None
        self._channel_id = None
        self._channel_name = None
        self._buffer = StringIO()
        # parsing-related, see _parse()
        self._device_handler = device_handler
        self._parsing_state10 = 0
        self._parsing_pos10 = 0
        self._parsing_pos11 = 0
        self._parsing_state11 = 0
        self._expchunksize = 0
        self._curchunksize = 0
        self._inendpos = 0
        self._size_num_list = []
        self._message_list = []
        self._closing = threading.Event()

        self.logger = SessionLoggerAdapter(logger, {'session': self})
Exemple #7
0
 def __init__(self):
     '''
     initialize
     '''
     self.__t = None
     self.__chan = None
     self.__sock = None
     self.__temp_buf = ""
     Thread.__init__(self)
     self.setDaemon(True)
     self.__host_keys = paramiko.HostKeys()
     self.__wait_resp = Event()
     self.__wait_resp.clear()
     self.__wait_rept = Event()
     self.__wait_rept.clear()
     self.__response_buffer = ""
     self.__hello_buffer = ""
     self.__session_id = None
     self.__isCOMPLD = False
     self.__error_message = ""
     self.__isOpen = False
     self.__send_data = ""
     self.__protocol_ver = "1.0"
     self.__notification_list = []
     self.__wait_string = ("", {})
     self.__host_name = ""
     self.__exp_protocol_version = ""
     self.__notification_list_print = []
Exemple #8
0
    def test_wrong_number_of_fields(self):
        """
        hostdict should not have any entries if the number of fields is incorrect
        """
        hostdict = paramiko.HostKeys('broken_hostfile.temp')
        self.assertEqual(0, len(hostdict))

        """
Exemple #9
0
 def test_load(self):
     hostdict = paramiko.HostKeys("hostfile.temp")
     self.assertEqual(2, len(hostdict))
     self.assertEqual(1, len(list(hostdict.values())[0]))
     self.assertEqual(1, len(list(hostdict.values())[1]))
     fp = hexlify(hostdict["secure.example.com"]
                  ["ssh-rsa"].get_fingerprint()).upper()
     self.assertEqual(b"E6684DB30E109B67B70FF1DC5C7F1363", fp)
Exemple #10
0
 def test_clear(self):
     hostdict = paramiko.HostKeys()
     hh = '|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c='
     key = paramiko.RSAKey(data=decodebytes(keyblob))
     hostdict.add(hh, 'ssh-rsa', key)
     self.assertEqual(1, len(list(hostdict)))
     hostdict.clear()
     self.assertEqual(0, len(list(hostdict)))
 def __init__(self, capabilities):
     Session.__init__(self, capabilities)
     self._host_keys = paramiko.HostKeys()
     self._transport = None
     self._connected = False
     self._channel = None
     self._buffer = StringIO()  # for incoming data
     # parsing-related, see _parse()
     self._parsing_state = 0
     self._parsing_pos = 0
Exemple #12
0
 def test_add(self):
     hostdict = paramiko.HostKeys("hostfile.temp")
     hh = "|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c="
     key = paramiko.RSAKey(data=decodebytes(keyblob))
     hostdict.add(hh, "ssh-rsa", key)
     self.assertEqual(3, len(list(hostdict)))
     x = hostdict["foo.example.com"]
     fp = hexlify(x["ssh-rsa"].get_fingerprint()).upper()
     self.assertEqual(b"7EC91BB336CB6D810B124B1353C32396", fp)
     self.assertTrue(hostdict.check("foo.example.com", key))
Exemple #13
0
 def test_delitem(self):
     hostdict = paramiko.HostKeys('hostfile.temp')
     target = 'happy.example.com'
     entry = hostdict[target] # will KeyError if not present
     del hostdict[target]
     try:
         entry = hostdict[target]
     except KeyError:
         pass # Good
     else:
         assert False, "Entry was not deleted from HostKeys on delitem!"
Exemple #14
0
def SunucuKomut():
	keyayarlari = paramiko.HostKeys()
	keyayarlari.load("/home/aloneft/.ssh/id_rsa")
	keyayarlari.lookup("server IP") 
	t = paramiko.Transport("server IP")
	t = paramiko.Transport(("server IP"))
	t.start_client()
	host_key = t.get_remote_server_key()
	keyayarlari.add("server IP", host_key.get_name(), host_key())
	keyayarlari.save("/home/aloneft/Desktop/known_hosts")
	istemci.load_system_host_keys()
	test = istemci.connect("server IP" , port = 22, username = "******" , password = "******" )
def check_ssh(opts, args):
    try:
        server_name = args.pop(0)
    except IndexError:
        raise Result(nagios.NAGIOS_STATUS_WTF,
                'You must provide a hostname.')

    try:
        hosts = paramiko.HostKeys(filename=opts.known_hosts_file)
    except IOError, detail:
        raise Result(nagios.NAGIOS_STATUS_WTF,
                '%s: %s' % (opts.known_hosts_file, detail.strerror))
Exemple #16
0
def send() -> None:
    """Main entry point for send command.

    Sends all curated files to the remote FTP server.
    """

    # Load curation files objects
    trembl_files = TrEMBLFiles()
    new_files = NewFiles()
    pep_files = PepFiles()
    sub_files = SubFiles()
    logfiles = LogFiles()
    pid_files = PidFiles()
    seq_files = SeqFiles()

    # Load FTP credentials
    try:
        remote_server = os.environ["REMOTE_SERVER"]
        remote_user = os.environ["REMOTE_USER"]
        remote_key = os.environ["REMOTE_KEY"]
        known_hosts = os.environ["KNOWN_HOSTS"]
    except KeyError as err:
        raise click.ClickException(
            f"Could not detect an environment variable for {err}s.")

    # Create SFTP connection and do the transfers
    try:
        key = paramiko.Ed25519Key.from_private_key_file(remote_key)
    except FileNotFoundError as err:
        raise click.ClickException(
            f"There was a problem loading the remote key file, please check your configuration:\n{err}"
        )

    try:
        hostkeys = paramiko.HostKeys(filename=known_hosts)
        hkey = hostkeys[remote_server]["ecdsa-sha2-nistp256"]
    except FileNotFoundError as err:
        raise click.ClickException(
            f"There was a problem loading the known hosts file, please check your configuration:\n{err}"
        )
    except KeyError as err:
        raise click.ClickException(
            f"Host {str(err)} not found in known_hosts file.")

    transport = paramiko.Transport((remote_server, 22))
    transport.connect(username=remote_user, pkey=key, hostkey=hkey)
    with paramiko.SFTPClient.from_transport(transport) as sftp:
        new_entries = [trembl_files, new_files, pep_files, sub_files]
        _send_new_entries(new_entries, sftp)
        for updates in [logfiles, pid_files, seq_files]:
            _send_updates(updates, sftp)
    transport.close()
Exemple #17
0
 def test_3_dict(self):
     hostdict = paramiko.HostKeys('hostfile.temp')
     self.assert_('secure.example.com' in hostdict)
     self.assert_('not.example.com' not in hostdict)
     self.assert_(hostdict.has_key('secure.example.com'))
     self.assert_(not hostdict.has_key('not.example.com'))
     x = hostdict.get('secure.example.com', None)
     self.assert_(x is not None)
     fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper()
     self.assertEquals('E6684DB30E109B67B70FF1DC5C7F1363', fp)
     i = 0
     for key in hostdict:
         i += 1
     self.assertEquals(2, i)
Exemple #18
0
 def test_dict(self):
     hostdict = paramiko.HostKeys("hostfile.temp")
     self.assertTrue("secure.example.com" in hostdict)
     self.assertTrue("not.example.com" not in hostdict)
     self.assertTrue("secure.example.com" in hostdict)
     self.assertTrue("not.example.com" not in hostdict)
     x = hostdict.get("secure.example.com", None)
     self.assertTrue(x is not None)
     fp = hexlify(x["ssh-rsa"].get_fingerprint()).upper()
     self.assertEqual(b"E6684DB30E109B67B70FF1DC5C7F1363", fp)
     i = 0
     for key in hostdict:
         i += 1
     self.assertEqual(2, i)
Exemple #19
0
 def __init__(self, device_handler):
     capabilities = Capabilities(device_handler.get_capabilities())
     Session.__init__(self, capabilities)
     self._host_keys = paramiko.HostKeys()
     self._transport = None
     self._connected = False
     self._channel = None
     self._channel_id = None
     self._channel_name = None
     self._buffer = StringIO()  # for incoming data
     # parsing-related, see _parse()
     self._parsing_state = 0
     self._parsing_pos = 0
     self._device_handler = device_handler
Exemple #20
0
    def test_entry_delitem(self):
        hostdict = paramiko.HostKeys('hostfile.temp')
        target = 'happy.example.com'
        entry = hostdict[target]
        key_type_list = [key_type for key_type in entry]
        for key_type in key_type_list:
            del entry[key_type]

        # will KeyError if not present
        for key_type in key_type_list:
            try:
                del entry[key_type]
            except KeyError:
                pass  # Good
            else:
                assert False, "Key was not deleted from Entry on delitem!"
Exemple #21
0
def update_kh(vm, vm_dns):

    # print("in create_vm")

    # wait for sshd
    # we can do this or just use while loop below
    # until we get the connection
    # time.sleep(5)

    # for vm in vm_dns:

    # print(vm)

    paramiko.util.log_to_file("aws_ssh.log")

    kh = os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))

    while True:
        try:
            t = paramiko.Transport(vm, 22)
            t.connect()
        except ssh_exception.SSHException:
            # this will print a lot without the above time.sleep
            # print("problem with ssh connection to " + vm)
            continue
        else:
            print("connected to " + vm + "\n")

        try:
            key = t.get_remote_server_key()
            print("got host key from " + vm + "\n")
        except ssh_exception.SSHException:
            print("failed to get host key from " + vm + "\n")
            continue
        else:
            t.close()
            print("connected closed with " + vm + "\n")

        try:
            hostfile = paramiko.HostKeys(filename=kh)
        except paramiko.hostkeys.HostKeyEntry.InvalidHostKey:
            pass
        else:
            hostfile.add(hostname=vm, key=key, keytype=key.get_name())
            hostfile.save(filename=kh)
            print("added " + vm + " to " + kh + "\n")
            break
Exemple #22
0
    def __init__(self, device_handler):
        capabilities = Capabilities(device_handler.get_capabilities())
        Session.__init__(self, capabilities)
        self._host = None
        self._host_keys = paramiko.HostKeys()
        self._transport = None
        self._connected = False
        self._channel = None
        self._channel_id = None
        self._channel_name = None
        self._buffer = StringIO()
        self._device_handler = device_handler
        self._message_list = []
        self._closing = threading.Event()
        self.parser = DefaultXMLParser(self)  # SAX or DOM parser

        self.logger = SessionLoggerAdapter(logger, {'session': self})
Exemple #23
0
    def test_4_dict_set(self):
        hostdict = paramiko.HostKeys('hostfile.temp')
        key = paramiko.RSAKey(data=base64.decodestring(keyblob))
        key_dss = paramiko.DSSKey(data=base64.decodestring(keyblob_dss))
        hostdict['secure.example.com'] = {'ssh-rsa': key, 'ssh-dss': key_dss}
        hostdict['fake.example.com'] = {}
        hostdict['fake.example.com']['ssh-rsa'] = key

        self.assertEquals(3, len(hostdict))
        self.assertEquals(2, len(hostdict.values()[0]))
        self.assertEquals(1, len(hostdict.values()[1]))
        self.assertEquals(1, len(hostdict.values()[2]))
        fp = hexlify(hostdict['secure.example.com']
                     ['ssh-rsa'].get_fingerprint()).upper()
        self.assertEquals('7EC91BB336CB6D810B124B1353C32396', fp)
        fp = hexlify(hostdict['secure.example.com']
                     ['ssh-dss'].get_fingerprint()).upper()
        self.assertEquals('4478F0B9A23CC5182009FF755BC1D26C', fp)
Exemple #24
0
    def test_dict_set(self):
        hostdict = paramiko.HostKeys("hostfile.temp")
        key = paramiko.RSAKey(data=decodebytes(keyblob))
        key_dss = paramiko.DSSKey(data=decodebytes(keyblob_dss))
        hostdict["secure.example.com"] = {"ssh-rsa": key, "ssh-dss": key_dss}
        hostdict["fake.example.com"] = {}
        hostdict["fake.example.com"]["ssh-rsa"] = key

        self.assertEqual(3, len(hostdict))
        self.assertEqual(2, len(list(hostdict.values())[0]))
        self.assertEqual(1, len(list(hostdict.values())[1]))
        self.assertEqual(1, len(list(hostdict.values())[2]))
        fp = hexlify(hostdict["secure.example.com"]
                     ["ssh-rsa"].get_fingerprint()).upper()
        self.assertEqual(b"7EC91BB336CB6D810B124B1353C32396", fp)
        fp = hexlify(hostdict["secure.example.com"]
                     ["ssh-dss"].get_fingerprint()).upper()
        self.assertEqual(b"4478F0B9A23CC5182009FF755BC1D26C", fp)
    def test_connect_wrong_input(self, stdout_mock, input_mock):

        key_io = StringIO("""-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACB69SvZKJh/9VgSL0G27b5xVYa8nethH3IERbi0YqJDXwAAAKhjwAdrY8AH
awAAAAtzc2gtZWQyNTUxOQAAACB69SvZKJh/9VgSL0G27b5xVYa8nethH3IERbi0YqJDXw
AAAEA9tGQi2IrprbOSbDCF+RmAHd6meNSXBUQ2ekKXm4/8xnr1K9komH/1WBIvQbbtvnFV
hryd62EfcgRFuLRiokNfAAAAI2FsZXhfZ2F5bm9yQEFsZXhzLU1hY0Jvb2stQWlyLmxvY2
FsAQI=
            -----END OPENSSH PRIVATE KEY-----""")
        key = paramiko.Ed25519Key.from_private_key(key_io)
        hostname = "0.0.0.0"
        key_type = key.get_name().replace("ssh-", "").upper()
        inputs = ["asd", "yes", "yoo", "no"]
        input_mock.side_effect = inputs
        ssh_connection = SSHConnection(hostname=hostname,
                                       known_hosts_file=self.known_hosts_file)
        ssh_connection._socket = paramiko.SSHClient()

        with self.assertLogs("gvm.connections", level="INFO") as cm:
            hostkeys = paramiko.HostKeys(filename=self.known_hosts_file)
            ssh_connection._ssh_authentication_input_loop(hostkeys=hostkeys,
                                                          key=key)
            ret = stdout_mock.getvalue()

            self.assertEqual(
                cm.output,
                [
                    "INFO:gvm.connections:Warning: "
                    f"Host '{hostname}' ({key_type}) not added to "
                    "the list of known hosts."
                ],
            )

            self.assertEqual(
                ret,
                f"The authenticity of host '{hostname}' can't be established.\n"
                f"{key_type} key fingerprint is "
                "J6VESFdD3xSChn8y9PzWzeF+1tl892mOy2TqkMLO4ow.\n"
                "Are you sure you want to continue connecting (yes/no)? "
                "Please type 'yes' or 'no': "
                "Do you want to add 0.0.0.0 to known_hosts (yes/no)? "
                "Please type 'yes' or 'no': ",
            )
    def test_connect_adding_and_dont_save_hostkey(self, input_mock):

        key_io = StringIO("""-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACB69SvZKJh/9VgSL0G27b5xVYa8nethH3IERbi0YqJDXwAAAKhjwAdrY8AH
awAAAAtzc2gtZWQyNTUxOQAAACB69SvZKJh/9VgSL0G27b5xVYa8nethH3IERbi0YqJDXw
AAAEA9tGQi2IrprbOSbDCF+RmAHd6meNSXBUQ2ekKXm4/8xnr1K9komH/1WBIvQbbtvnFV
hryd62EfcgRFuLRiokNfAAAAI2FsZXhfZ2F5bm9yQEFsZXhzLU1hY0Jvb2stQWlyLmxvY2
FsAQI=
            -----END OPENSSH PRIVATE KEY-----""")
        key = paramiko.Ed25519Key.from_private_key(key_io)
        key_type = key.get_name().replace("ssh-", "").upper()
        hostname = "0.0.0.0"
        input_mock.side_effect = ["yes", "no"]
        ssh_connection = SSHConnection(hostname=hostname,
                                       known_hosts_file=self.known_hosts_file)
        ssh_connection._socket = paramiko.SSHClient()
        keys = self.known_hosts_file.read_text(encoding="utf-8")
        self.assertEqual(
            keys,
            "127.0.0.1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBOZWi"
            "fs+DoMqIa5Nr0wiVrzQNpMbUwaLzuSTN6rNrYA\n",
        )

        with self.assertLogs("gvm.connections", level="INFO") as cm:
            hostkeys = paramiko.HostKeys(filename=self.known_hosts_file)
            ssh_connection._ssh_authentication_input_loop(hostkeys=hostkeys,
                                                          key=key)
            keys = self.known_hosts_file.read_text(encoding="utf-8")

            self.assertEqual(
                cm.output,
                [
                    "INFO:gvm.connections:Warning: "
                    f"Host '{hostname}' ({key_type}) not added to "
                    "the list of known hosts."
                ],
            )

            self.assertEqual(
                keys,
                "127.0.0.1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBOZWi"
                "fs+DoMqIa5Nr0wiVrzQNpMbUwaLzuSTN6rNrYA\n",
            )
Exemple #27
0
 def __init__(self, device_handler):
     capabilities = Capabilities(device_handler.get_capabilities())
     Session.__init__(self, capabilities)
     self._host_keys = paramiko.HostKeys()
     self._transport = None
     self._connected = False
     self._channel = None
     self._channel_id = None
     self._channel_name = None
     self._buffer = StringIO()  # for incoming data
     # parsing-related, see _parse()
     self._device_handler = device_handler
     self._parsing_state10 = 0
     self._parsing_pos10 = 0
     self._parsing_pos11 = 0
     self._parsing_state11 = 0
     self._expchunksize = 0
     self._curchunksize = 0
     self._inendpos = 0
     self._size_num_list = []
     self._message_list = []
    def test_user_denies_auth(self, input_mock):

        key_io = StringIO("""-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACB69SvZKJh/9VgSL0G27b5xVYa8nethH3IERbi0YqJDXwAAAKhjwAdrY8AH
awAAAAtzc2gtZWQyNTUxOQAAACB69SvZKJh/9VgSL0G27b5xVYa8nethH3IERbi0YqJDXw
AAAEA9tGQi2IrprbOSbDCF+RmAHd6meNSXBUQ2ekKXm4/8xnr1K9komH/1WBIvQbbtvnFV
hryd62EfcgRFuLRiokNfAAAAI2FsZXhfZ2F5bm9yQEFsZXhzLU1hY0Jvb2stQWlyLmxvY2
FsAQI=
            -----END OPENSSH PRIVATE KEY-----""")
        key = paramiko.Ed25519Key.from_private_key(key_io)
        hostname = "0.0.0.0"
        input_mock.return_value = "no"
        ssh_connection = SSHConnection(hostname=hostname,
                                       known_hosts_file=self.known_hosts_file)
        ssh_connection._socket = paramiko.SSHClient()

        with self.assertRaises(
                SystemExit,
                msg="User denied key. Host key verification failed."):
            hostkeys = paramiko.HostKeys(filename=self.known_hosts_file)
            ssh_connection._ssh_authentication_input_loop(hostkeys=hostkeys,
                                                          key=key)
Exemple #29
0
parser = argparse.ArgumentParser()
parser.add_argument('host', action='store', help='host to connect to')
parser.add_argument('-p',
                    '--port',
                    action='store',
                    dest='port',
                    default='22',
                    help='port to connect to')
parser.add_argument('--known_hosts',
                    action='store',
                    dest='known_hosts',
                    default='~/.ssh/known_hosts',
                    help='known_hosts file')
args = parser.parse_args()

host = args.host
port = args.port
known_hosts = os.path.expanduser(args.known_hosts)

transport = paramiko.Transport(host, port)

transport.connect()
key = transport.get_remote_server_key()
print(key.get_base64())
transport.close()

hostfile = paramiko.HostKeys(filename=known_hosts)
hostfile.add(hostname=host, key=key, keytype=key.get_name())

hostfile.save(filename=known_hosts)
    def __init__(self,
                 local_path,
                 remote_url,
                 identity_files=None,
                 port=None,
                 fix_symlinks=False,
                 ssh_config_path=None,
                 ssh_agent=False,
                 exclude_file=None,
                 known_hosts_path=None,
                 delete=True,
                 allow_unknown=False):
        """Init the needed parameters and the SFTPClient."""
        self.local_path = os.path.realpath(os.path.expanduser(local_path))
        self.logger = logger or configure_logging()

        if not os.path.exists(self.local_path):
            self.logger.error("Local path MUST exist. Exiting.")
            sys.exit(1)

        if exclude_file:
            with open(exclude_file) as f:
                # As in rsync's exclude from, ignore lines with leading ; and #
                # and treat each path as relative (thus by removing the leading
                # /)
                exclude_list = [
                    line.rstrip().lstrip("/") for line in f
                    if not line.startswith((";", "#"))
                ]

                # actually, is a set of excluded files
                self.exclude_list = {
                    g
                    for pattern in exclude_list
                    for g in glob.glob(path_join(self.local_path, pattern))
                }
        else:
            self.exclude_list = set()

        username, password, hostname, self.remote_path = parse_username_password_hostname(
            remote_url)

        identity_files = identity_files or []
        proxy_command = None
        if ssh_config_path:
            try:
                with open(os.path.expanduser(ssh_config_path)) as c_file:
                    ssh_config = paramiko.SSHConfig()
                    ssh_config.parse(c_file)
                    c = ssh_config.lookup(hostname)

                    hostname = c.get("hostname", hostname)
                    username = c.get("user", username)
                    port = int(c.get("port", port))
                    identity_files = c.get("identityfile", identity_files)
                    proxy_command = c.get("proxycommand")
            except Exception as e:
                # it could be safe to continue anyway,
                # because parameters could have been manually specified
                self.logger.error(
                    "Error while parsing ssh_config file: %s. Trying to continue anyway...",
                    e)

        # Set default values
        if not username:
            username = getuser()  # defaults to current user

        port = port or 22
        allow_unknown = allow_unknown or False

        self.chown = False
        self.fix_symlinks = fix_symlinks or False
        self.delete = delete if delete is not None else True

        if ssh_agent:
            agent, agent_keys = get_ssh_agent_keys(self.logger)
        else:
            agent, agent_keys = None, None

        if not identity_files and not password and not agent_keys:
            self.logger.error(
                "You need to specify either a password, an identity or to enable the ssh-agent support."
            )
            sys.exit(1)

        # only root can change file owner
        if username == 'root':
            self.chown = True

        sock = (hostname, port)
        if proxy_command is not None:
            sock = paramiko.proxy.ProxyCommand(proxy_command)

        try:
            transport = paramiko.Transport(sock)
        except socket.gaierror:
            self.logger.error(
                "Hostname not known. Are you sure you inserted it correctly?")
            sys.exit(1)

        try:
            ssh_host = hostname if port == 22 else "[{}]:{}".format(
                hostname, port)
            known_hosts = None
            """
            Before starting the transport session, we have to configure it.
            Specifically, we need to configure the preferred PK algorithm.
            If the system already knows a public key of a specific kind for
            a remote host, we have to peek its type as the preferred one.
            """
            if known_hosts_path:
                known_hosts = paramiko.HostKeys()
                known_hosts_path = os.path.realpath(
                    os.path.expanduser(known_hosts_path))

                try:
                    known_hosts.load(known_hosts_path)
                except IOError:
                    self.logger.error(
                        "Error while loading known hosts file at {}. Exiting..."
                        .format(known_hosts_path))
                    sys.exit(1)

                known_keys = known_hosts.lookup(ssh_host)
                if known_keys is not None:
                    # one or more keys are already known
                    # set their type as preferred
                    transport.get_security_options().key_types = \
                        tuple(known_keys.keys())

            transport.start_client()

            if not known_hosts:
                self.logger.warning(
                    "Security warning: skipping known hosts check...")
            else:
                pubk = transport.get_remote_server_key()
                if ssh_host in known_hosts.keys():
                    if not known_hosts.check(ssh_host, pubk):
                        self.logger.error(
                            "Security warning: "
                            "remote key fingerprint {} for hostname "
                            "{} didn't match the one in known_hosts {}. "
                            "Exiting...".format(
                                pubk.get_base64(),
                                ssh_host,
                                known_hosts.lookup(hostname),
                            ))
                        sys.exit(1)
                elif not allow_unknown:
                    prompt = (
                        "The authenticity of host '{}' can't be established.\n"
                        "{} key is {}.\n"
                        "Are you sure you want to continue connecting? [y/n] "
                    ).format(ssh_host, pubk.get_name(), pubk.get_base64())

                    try:
                        # Renamed to `input` in Python 3.x
                        response = raw_input(prompt)
                    except NameError:
                        response = input(prompt)

                    # Note: we do not modify the user's known_hosts file

                    if not (response == "y" or response == "yes"):
                        self.logger.error("Host authentication failed.")
                        sys.exit(1)

            def perform_key_auth(pkey):
                try:
                    transport.auth_publickey(username=username, key=pkey)
                    return True
                except paramiko.SSHException:
                    self.logger.warning(
                        "Authentication with identity {}... failed".format(
                            pkey.get_base64()[:10]))
                    return False

            if password:  # Password auth, if specified.
                transport.auth_password(username=username, password=password)
            elif agent_keys:  # SSH agent keys have higher priority
                for pkey in agent_keys:
                    if perform_key_auth(pkey):
                        break  # Authentication worked.
                else:  # None of the keys worked.
                    raise paramiko.SSHException
            elif identity_files:  # Then follow identity file (specified from CL or ssh_config)
                # Try identity files one by one, until one works
                for key_path in identity_files:
                    key_path = os.path.expanduser(key_path)

                    try:
                        key = paramiko.RSAKey.from_private_key_file(key_path)
                    except paramiko.PasswordRequiredException:
                        pk_password = getpass(
                            "It seems that your identity from '{}' is encrypted. "
                            "Please enter your password: "******"Incorrect passphrase. Cannot decode private key from '{}'."
                                .format(key_path))
                            continue
                    except IOError or paramiko.SSHException:
                        self.logger.error(
                            "Something went wrong while opening '{}'. Skipping it."
                            .format(key_path))
                        continue

                    if perform_key_auth(key):
                        break  # Authentication worked.

                else:  # None of the keys worked.
                    raise paramiko.SSHException
            else:  # No authentication method specified, we shouldn't arrive here.
                assert False
        except paramiko.SSHException:
            self.logger.error(
                "None of the provided authentication methods worked. Exiting.")
            transport.close()
            sys.exit(1)
        finally:
            if agent:
                agent.close()

        self.sftp = paramiko.SFTPClient.from_transport(transport)

        if self.remote_path.startswith("~"):
            # nasty hack to let getcwd work without changing dir!
            self.sftp.chdir('.')
            self.remote_path = self.remote_path.replace(
                "~", self.sftp.getcwd())  # home is the initial sftp dir