Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate ssh commands with python [closed]

Tags:

python

linux

ssh

So everyday, I need to login to a couple different hosts via ssh and run some maintenance commands there in order for the QA team to be able to test my features.

I want to use a python script to automate such boring tasks. It would be something like:

  • ssh host1
  • deploy stuff
  • logout from host1
  • ssh host2
  • restart stuff
  • logout from host2
  • ssh host3
  • check health on stuff
  • logout from host3
  • ...

It's killing my productivity, and I would like to know if there is something nice, ergonomic and easy to implement that can handle and run commands on ssh sessions programmatically and output a report for me.

Of course I will do the code, I just wanted some suggestions that are not bash scripts (because those are not meant for humans to be read).

like image 504
RicardoE Avatar asked Feb 05 '23 01:02

RicardoE


1 Answers

You can use the following things programmatically:

  • For low-level SSH automation - Paramiko
  • For somewhat higher-level automation - Fabric

Alternatively, if your activities are all around automation of typical sysadmin tasks - have a look at orchestration tools:

  • Ansible
  • Saltstack

To give an example in Fabric, define a task to login to a host and run uname -a:

from fabric import *
from fabric.api import *

env.hosts = ['localhost']

def login_to_host_and_run_uname():
    run('uname -a')

You can run it as a standalone fabric command:

[none][20:03:32] vlazarenko@alluminium (~/tests)$ fab -f fab.py login_to_host_and_run_uname
[localhost] Executing task 'login_to_host_and_run_uname'
[localhost] run: uname -a
[localhost] Passphrase for private key:
[localhost] out: Darwin alluminium 16.5.0 Darwin Kernel Version 16.5.0: Tue Jan 31 18:57:20 PST 2017; root:xnu-3789.50.195.1.1~1/RELEASE_X86_64 x86_64
[localhost] out:


Done.
Disconnecting from localhost... done.

Fabric also supports easy wrappers for sudo(), caches and works with SSH keys, etc, etc. Allows for easy task parallelisation over multiple hosts and so on.

like image 154
favoretti Avatar answered Feb 08 '23 14:02

favoretti