123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- """Paramiko SSH support for Dulwich.
- To use this implementation as the SSH implementation in Dulwich, override
- the dulwich.client.get_ssh_vendor attribute:
- >>> from dulwich import client as _mod_client
- >>> from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
- >>> _mod_client.get_ssh_vendor = ParamikoSSHVendor
- This implementation is experimental and does not have any tests.
- """
- import paramiko
- import paramiko.client
- class _ParamikoWrapper:
- def __init__(self, client, channel) -> None:
- self.client = client
- self.channel = channel
-
- self.channel.setblocking(True)
- @property
- def stderr(self):
- return self.channel.makefile_stderr("rb")
- def can_read(self):
- return self.channel.recv_ready()
- def write(self, data):
- return self.channel.sendall(data)
- def read(self, n=None):
- data = self.channel.recv(n)
- data_len = len(data)
-
- if not data:
- return b""
-
- if n and data_len < n:
- diff_len = n - data_len
- return data + self.read(diff_len)
- return data
- def close(self):
- self.channel.close()
- class ParamikoSSHVendor:
-
- def __init__(self, **kwargs) -> None:
- self.kwargs = kwargs
- def run_command(
- self,
- host,
- command,
- username=None,
- port=None,
- password=None,
- pkey=None,
- key_filename=None,
- **kwargs,
- ):
- client = paramiko.SSHClient()
- connection_kwargs = {"hostname": host}
- connection_kwargs.update(self.kwargs)
- if username:
- connection_kwargs["username"] = username
- if port:
- connection_kwargs["port"] = port
- if password:
- connection_kwargs["password"] = password
- if pkey:
- connection_kwargs["pkey"] = pkey
- if key_filename:
- connection_kwargs["key_filename"] = key_filename
- connection_kwargs.update(kwargs)
- policy = paramiko.client.MissingHostKeyPolicy()
- client.set_missing_host_key_policy(policy)
- client.connect(**connection_kwargs)
-
- channel = client.get_transport().open_session()
-
- channel.exec_command(command)
- return _ParamikoWrapper(client, channel)
|