Created
April 24, 2018 04:43
-
-
Save mu-777/7e4ef69a7e30b2ab79e0792af9db1fd8 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
class FileTailer(object): | |
def __init__(self, ip, port, username, password): | |
self._ip, self._port, self._user, self._pass = ip, port, username, password | |
self._stdout = None | |
def start(self, remote_filepath, timeout_sec=60): | |
if (not isinstance(timeout_sec, int)) or (timeout_sec < 0): | |
timeout_sec = None | |
if self._stdout is not None: | |
self.close() | |
self._stdout = None | |
self._ssh = SSHClient() | |
self._ssh.set_missing_host_key_policy(AutoAddPolicy()) | |
self._ssh.connect(hostname=self._ip, port=self._port, | |
username=self._user, password=self._pass) | |
_, self._stdout, _ = self._ssh.exec_command('tail -f {0}'.format(remote_filepath), | |
get_pty=True, timeout=timeout_sec) | |
return self | |
@property | |
def is_readable(self): | |
return (self._stdout is not None) and (not self._stdout.channel.closed) | |
def readline(self): | |
l = self._stdout.readline() | |
if l != '': | |
yield l | |
def close(self): | |
if self._stdout is not None: | |
self._ssh.close() | |
self._stdout.channel.close() | |
def tailer_test(filepath): | |
tailer = FileTailer('192.168.100.16', 22, 'root', 'root') | |
tailer.start(filepath, timeout_sec=-1) | |
while tailer.is_readable: | |
try: | |
for l in tailer.readline(): | |
print l | |
except KeyboardInterrupt as e: | |
print 'Closed: KeyboardInterrupt' | |
tailer.close() | |
break | |
else: | |
print 'Closed: File is Not Readable Now' | |
tailer.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment