Skip to content

Instantly share code, notes, and snippets.

@mu-777
Created April 24, 2018 04:43
Show Gist options
  • Save mu-777/7e4ef69a7e30b2ab79e0792af9db1fd8 to your computer and use it in GitHub Desktop.
Save mu-777/7e4ef69a7e30b2ab79e0792af9db1fd8 to your computer and use it in GitHub Desktop.
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