Skip to content

Commit

Permalink
Fix SSH #1633
Browse files Browse the repository at this point in the history
  • Loading branch information
micafer committed Nov 14, 2024
1 parent 50e8829 commit 01f2e7d
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions IM/SSH.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,10 @@ def __init__(self, host, user, passwd=None, private_key=None, port=22, proxy_hos
private_key_obj = StringIO()
if os.path.isfile(private_key):
pkfile = open(private_key)
self.private_key = ""
for line in pkfile.readlines():
private_key_obj.write(line)
self.private_key += line
pkfile.close()
else:
# Avoid windows line endings
Expand All @@ -128,18 +130,31 @@ def __init__(self, host, user, passwd=None, private_key=None, port=22, proxy_hos
if not private_key.endswith("\n"):
private_key += "\n"
private_key_obj.write(private_key)
self.private_key = private_key

self.private_key = private_key
private_key_obj.seek(0)
self.private_key_obj = self._load_private_key(private_key_obj)

if "BEGIN RSA PRIVATE KEY" in private_key:
self.private_key_obj = paramiko.RSAKey.from_private_key(private_key_obj)
elif "BEGIN DSA PRIVATE KEY" in private_key:
self.private_key_obj = paramiko.DSSKey.from_private_key(private_key_obj)
elif "BEGIN EC PRIVATE KEY" in private_key:
self.private_key_obj = paramiko.ECDSAKey.from_private_key(private_key_obj)
elif "BEGIN OPENSSH PRIVATE KEY" in private_key:
self.private_key_obj = paramiko.Ed25519Key.from_private_key(private_key_obj)
@staticmethod
def _load_private_key(private_key_obj):
""" Load a private key from a file-like object"""
private_key_obj.seek(0)
try:
return paramiko.RSAKey.from_private_key(private_key_obj)
except Exception:
private_key_obj.seek(0)
try:
return paramiko.DSSKey.from_private_key(private_key_obj)
except Exception:
private_key_obj.seek(0)
try:
return paramiko.ECDSAKey.from_private_key(private_key_obj)
except Exception:
private_key_obj.seek(0)
try:
return paramiko.Ed25519Key.from_private_key(private_key_obj)
except Exception:
private_key_obj.seek(0)
raise Exception("Invalid private key")

def __del__(self):
self.close()
Expand Down

0 comments on commit 01f2e7d

Please sign in to comment.