Last active
August 11, 2016 16:27
-
-
Save webs86/21b873140432cb973890f52ce01b53fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import paramiko | |
from django.utils import timezone | |
class SSHBaseCommand: | |
shell = None | |
client = None | |
transport = None | |
commands = [] | |
cmd = '' | |
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 = paramiko.Transport((address, 22)) | |
self.transport.connect(username=username, password=password) | |
def close_connection(self): | |
if self.client is not None: | |
self.client.close() | |
self.transport.close() | |
def _open_shell(self): | |
self.shell = self.client.invoke_shell() | |
def send_cmd(self, command): | |
if self.shell is None: | |
self._open_shell() | |
cmd = dict() | |
cmd['command'] = command | |
cmd['start_time'] = timezone.now() | |
self.shell.send(command + "\n") | |
alldata = self.shell.recv(1024) | |
while self.shell.recv_ready(): | |
alldata += self.shell.recv(1024) | |
strdata = str(alldata, "utf8") | |
strdata.replace('\r', '') | |
cmd['output'] = strdata | |
cmd['end_time'] = timezone.now() | |
self.commands.append(cmd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment