@@ -50,8 +50,41 @@ def __init__(self, host, **ssh_kwargs):
5050 def _connect (self ):
5151 logger .debug ("Connecting to SFTP server %s" , self .host )
5252 self .client = paramiko .SSHClient ()
53- self .client .set_missing_host_key_policy (paramiko .AutoAddPolicy ())
54- self .client .connect (self .host , ** self .ssh_kwargs )
53+ self .config = paramiko .SSHConfig .from_path (os .path .expanduser ("~/.ssh/config" )).lookup (self .host )
54+ if "hostname" in self .config :
55+ self .host = self .config ["hostname" ]
56+
57+ # Can be yes, no, or ask (case-insensitive). Ask is not supported. RejectPolicy is the default.
58+ if "StrictHostKeyChecking" .lower () in self .config and self .config ["stricthostkeychecking" ].lower () == "no" :
59+ self .client .set_missing_host_key_policy (paramiko .AutoAddPolicy ())
60+
61+ known_host_keys_file = "~/.ssh/known_hosts"
62+ if "UserKnownHostsFile" .lower () in self .config :
63+ known_host_keys_file = self .config ["UserKnownHostsFile" .lower ()]
64+ try :
65+ self .client .load_system_host_keys (os .path .expanduser (known_host_keys_file ))
66+ except (FileNotFoundError , PermissionError ):
67+ pass
68+
69+ # Dictionary to map ssh_config keys to paramiko.Client.connect argument names.
70+ key_mappings = {
71+ "Port" : ("port" , lambda x : int (x )),
72+ "User" : ("username" , lambda x : x ),
73+ "Compression" : ("compress" , lambda x : x .lower () == "yes" ),
74+ "IdentityFile" : ("key_filename" , lambda x : x ),
75+ "IdentitiesOnly" : ("allow_agent" , lambda x : x .lower () == "no" ),
76+ "ConnectTimeout" : ("timeout" , lambda x : float (x )),
77+ }
78+ connect_options = self .ssh_kwargs .copy ()
79+ for config_key , value in key_mappings .items ():
80+ argument_name , converter = value
81+ if config_key .lower () in self .config and argument_name not in connect_options :
82+ connect_options [argument_name ] = converter (self .config [config_key .lower ()])
83+
84+ if "key_filename" in connect_options :
85+ connect_options ["look_for_keys" ] = False
86+
87+ self .client .connect (self .host , ** connect_options )
5588 self .ftp = self .client .open_sftp ()
5689
5790 @classmethod
0 commit comments