SSH using fabric module

Fabric is a Python library as well as a command-line tool for the use of SSH. It is used for system administration and application deployment over the network. We can also execute shell commands over SSH.

To use fabric module, first you have to install it using the following command:

$ pip3 install fabric3

Now, we will see an example. Create a fabfile.py script and write the following content in it:

from fabric.api import *

env.hosts=["host_name@host_ip"]
env.password='your password'

def dir():
run('mkdir fabric')
print('Directory named fabric has been created on your host network')

def diskspace():
run('df')

Run the script and you will get the output as follows:

student@ubuntu:~$ fab dir
Output:
[[email protected]] Executing task 'dir'
[[email protected]] run: mkdir fabric

Done.
Disconnecting from 192.168.0.106... done.

In the preceding example, first, we imported the fabric.api module, then we set the hostname and password to get connected with the host network. After that, we set different task to perform over SSH. Therefore, to execute our program instead of the Python3 fabfile.py, we used the fab utility (fab dir), and after that we stated that the required tasks should be performed from our fabfile.py.  In our case, we performed the dir task, which creates a directory with the name 'fabric' on your remote network. You can add your specific task in your Python file. It can be executed using the fab utility of the fabric module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset