Skip to content

Instantly share code, notes, and snippets.

@perillo
Forked from webs86/py_ssh.py
Last active August 22, 2016 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save perillo/8c492a6a021e71034b1c33fb085a6679 to your computer and use it in GitHub Desktop.
Save perillo/8c492a6a021e71034b1c33fb085a6679 to your computer and use it in GitHub Desktop.
import paramiko
BUF_SIZE = 8192
TIMEOUT = None
class SSHCommand:
def __init__(self, address, username, password):
print("Connecting to server on ip", str(address) + ".")
self._client = paramiko.client.SSHClient()
self._client.set_missing_host_key_policy(
paramiko.client.AutoAddPolicy())
self._client.connect(address, username=username, password=password,
look_for_keys=False)
self._transport = self._client.get_transport()
def close(self):
self._client.close()
def send_cmd(self, cmd):
chan = self._transport.open_session(timeout=TIMEOUT)
chan.settimeout(TIMEOUT)
chan.exec_command(cmd)
data = self._recv(chan)
status = chan.recv_exit_status()
return status, data
def _recv(self, chan):
buf = []
while True:
data = chan.recv(BUF_SIZE)
if data == b'':
break
data = data.decode("utf-8")
data = data.replace('\r', '')
buf.append(data)
return "".join(buf)
client = SSHCommand("localhost", ...)
data = client.send_cmd("ls /")
print(data)
data = client.send_cmd("ls /XXX")
print(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment