pythonlinuxfabric

How do I get output of "top" command using Python Fabric?


I am trying to automate monitoring services on remote host using Python Fabric from a host. I am able to get details from the remote servers using many of the Linux command using Fabric but the scripts fails getting the output of "top" , systemctl and few other commands. My code is as below

#!/usr/bin/env python
from fabric import Connection
c = Connection(host = 'root@172.30.205.61', connect_kwargs={'password' : 'Password!234'})
print('')
print('Output of Top command')
print('')
c.run('top')

I get the below error.

TERM environment variable not set.

Output of Top command

Traceback (most recent call last):
  File "./monitoring.py", line 11, in <module>
    c.run('top')
  File "<decorator-gen-3>", line 2, in run
  File "C:\Users\ganguly\AppData\Roaming\Python\Python38\site-packages\fabric\connection.py", line 30, in opens
    return method(self, *args, **kwargs)
  File "C:\Users\ganguly\AppData\Roaming\Python\Python38\site-packages\fabric\connection.py", line 725, in run
    return self._run(self._remote_runner(), command, **kwargs)
  File "C:\Users\ganguly\AppData\Roaming\Python\Python38\site-packages\invoke\context.py", line 102, in _run
    return runner.run(command, **kwargs)
  File "C:\Users\ganguly\AppData\Roaming\Python\Python38\site-packages\fabric\runners.py", line 72, in run
    return super(Remote, self).run(command, **kwargs)
  File "C:\Users\ganguly\AppData\Roaming\Python\Python38\site-packages\invoke\runners.py", line 379, in run
    return self._run_body(command, **kwargs)
  File "C:\Users\ganguly\AppData\Roaming\Python\Python38\site-packages\invoke\runners.py", line 441, in _run_body
    return self.make_promise() if self._asynchronous else self._finish()
  File "C:\Users\ganguly\AppData\Roaming\Python\Python38\site-packages\invoke\runners.py", line 508, in _finish
    raise UnexpectedExit(result)
invoke.exceptions.UnexpectedExit: Encountered a bad command exit code!

Command: 'top'

Exit code: 1

Stdout: already printed

Stderr: already printed

Solution

  • Add argument pty=True

    connection.run("top", hide=False, pty=True)