Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»Fabric Module in Python
    python

    Fabric Module in Python

    March 14, 2023No Comments27 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Fabric Module in Python Users of Linux are required to perform a variety of administrative and general tasks on a consistent basis. These tasks include reloading the Apache server after making any changes, developing and deploying new applications, accessing specific log files, and so on. SSH, also known as Secure Shell, is required in order to carry out these actions on a consistent basis. Fabric is a helpful Python module that can automate a variety of application development and administration tasks by collaborating with SSH and the operating system. This program’s command-line interface is simple and easy to understand and use. This tutorial will walk you through the steps of installing and using the fabric library in Python 3+.

    It does this by extending the application programming interfaces (APIs) of Invoke (which handles subprocess command execution and command-line features) and Paramiko (which implements the SSH protocol), which complements and provides additional capabilities. The person responsible for maintaining the project maintains a roadmap. The official website for the Fabric project contains information on the project, including the changelog and the prerequisites for contributions. Use and API documentation can be found in great detail on the site for code documentation, which is located at docs.fabfile.org.

    The paramiko library gives you the ability to perform ssh tasks that are fundamental or of a lower level. Fabric is a library that internally makes use of paramiko to carry out a variety of higher-level functions (for ssh purposes). In a nutshell, you should use paramiko if all you want to do is ssh. On the other hand, you should use fabric script if you want to do a lot more, such as running a configuration, installing something on the server, or deploying code. It will make your life simpler because you will be required to write fewer lines of code than you would be if you directly used paramiko. (and there is no need for alarm since paramiko is used on the inside of the cloth).

    In Python, Paramiko provides a straightforward and uncomplicated method for utilising SSH by way of an imported library. You will have the ability to create a “fabfile” and carry out the various instructions that are pre-programmed into the fabric. You have complete creative control over what this could become. To give you an example, on my personal computer I have a fabfile that links to the personal server, CDs into the appropriate directory, pulls the git branch in, transfers various configuration files to the appropriate places (uwsgi, Nginx), and restarts the appropriate services. As a direct result of this, I am able to publish the most recent version of my website to the internet by issuing a single command from my local PC. Additionally, the fabric is dependent on Paramiko in order to function properly.

    Since we now know that the paramiko module is used internally by the fabric library, let’s take a look at the paramiko module that is included in the Python library.

    The first step in the process of using the high-level client API is the creation of an SSHClient object. After you have given a socket, or an object that behaves like a socket, to a Transport in order to gain more direct control, use start server or start client in order to negotiate with the remote host as a server or client. As a client, it is your responsibility to authenticate yourself by providing a password or a private key in addition to verifying the host key of the server. (The process of signing and verifying a key is handled by Paramiko, but you will be required to provide private keys and verify that the information contained in a public key corresponds to what you intended.) As the server, it is your responsibility to choose which users, passwords, and keys to allow access, as well as which channels to activate. After you have finished it, any party may ask for flow-controlled channels to be opened.

    Next, let us take a look at the code that demonstrates how to use the fabric module in Python:

    Code::

    1. #A sample code to show the uses of fabric module in Python we have different functions to perform different operations on the remote site server the initial step of all these functions is to make a secure ssh connection to the remote side server 1st secure connection is established successfully the next step is to perform the specified operation in the corresponding function  
    2.   
    3. # the fabric module is imported which will be used to use various functions within this model  
    4. from fabric import Connection  
    5. #  the system module is also imported to use the exit function  
    6. import sys  
    7.   
    8. # this is the first function that will be used to create a working directory on the remote site server when we run this function it asks the user for the name of the directory that the user wants to create on the remote site server once the user provides the name of the directory that particular directory is created on the remote site server and the result is conveyed to reuse  
    9. def createWorkingDir():  
    10.     print(“Enter the name of the directory that you want to create”)  
    11.     dir_name = input()  
    12.     with Connection(“superbook”,user=“client”,connect_kwargs={“password”:“nirnay”}) as c:  
    13.         with c.cd(“/home/client/Desktop”):  
    14.             c.run(“mkdir {}”.format(dir_name))  
    15.             c.run(“ls {}”.format(dir_name))  
    16.   
    17.     print(“{} directory created sucessfully.”.format(dir_name))  
    18.   
    19. #  this is another function that we have written that is to operate changing a directory or moving to another directory on the remote site server on executing this function it asks for the name of the directory to which we want to move after adding the name of the directory the current execution of the code gets moved to the directory whose name is added by the user this function on its completion changes the current working directory of the program execution  
    20. def moveToDir():  
    21.     print(“Enter the name of the directory to which you want to move”)  
    22.     dir_name = input()  
    23.     with Connection(“superbook”,user=“client”,connect_kwargs={“password”:“nirnay”}) as c:  
    24.         with c.cd(“/home/client/Desktop/{}”.format(dir_name)):  
    25.             c.run(“pwd”)  
    26.   
    27.     print(“directory changed successfully”)  
    28.   
    29.   
    30. #This function is used to create new files on the remote site server on the execution of this function the user is prompted with a message asking for pee name of the directory in which the user wants to create the files after  specifying the name of the directory 10 demo files are created in that directory and on the successful creation of the files in the specified directory the user is prompted with the successful message confirming the successful creation of the files in a particular specified Directory on the remote  side server  
    31. def create files():  
    32.     print(“Enter the name of the directory in which you want to create files”)  
    33.     dir_name = input()  
    34.     with Connection(“superbook”,user=“client”,connect_kwargs={“password”:“nirnay”}) as c:  
    35.         with c.cd(“/home/client/Desktop/{}”.format(dir_name)):  
    36.             c.run(“touch files{1..15}”)  
    37.   
    38.     print(“Files created sucessfully in {} directory.”.format(dir_name))  
    39.   
    40. #  the main motive of this function is to list all the files that are present in a particular directory by adding the name of the directory whose files we want to list all the files that are present in that particular specified directory are listed and are displayed to the user point to be noted is that all the files getting list are present on the remote server not on the local machine  
    41. def listFilesInDir():  
    42.     print(“Enter the name of the directory in which you want to list files”)  
    43.     dir_name = input()  
    44.     with Connection(“superbook”,user=“client”,connect_kwargs={“password”:“nirnay”}) as c:  
    45.         with c.cd(“/home/client/Desktop/{}”.format(dir_name)):  
    46.             c.run(“ls”)  
    47.   
    48.     print(“Files listed sucessfully in {} directory.”.format(dir_name))  
    49.   
    50. # similar to the previous function this function is also used to list all the directories instead of the files the only difference between the previously written function and this function is that this function list all the directories inside a directory and the previous function list all the files inside  a directory similar to the previous function this function also asks for the name of the directory whose directories we want to list the directories which get listed are the children directories of the directory whose name is added by the user  
    51. def listAllDirs():  
    52.     with Connection(“superbook”,user=“client”,connect_kwargs={“password”:“nirnay”}) as c:  
    53.         with c.cd(“/home/client/Desktop”):  
    54.             c.run(“ls”)  
    55.   
    56.     print(“All dirs listed sucessfully.”)  
    57.   
    58. #  this function is a kind of combination of the above to return functions that will be used to list all the files as well as the directories from the current execution directory of the program the user can use this function instead of calling to separate above written functions that will return the same data which is is collectively returned by this function  print the  files and directories in the current working directory in a recursive manner that means if there is a directory inside a directory that the contents of the nested directories are also listed by this functions whether the contents are files or directories all of them will be listed with the use of thisfunction  
    59. def listAllDirsAndFilesInTreeMode():  
    60.     with Connection(“superbook”,user=“client”,connect_kwargs={“password”:“nirnay”}) as c:  
    61.         with c.cd(“/home/client/Desktop”):  
    62.             c.run(“tree .”)  
    63.   
    64.     print(“All dirs and files listed sucessfully.”)  
    65.   
    66.   
    67.   
    68. # In the end the main function is written to call all the above detail functions and verify their functionalities one by one by calling each of them each of them provide a separate unique operation on the remote site server by taking various inputs and providing different of food accordingly.   
    69. def main():  
    70.     while(True):  
    71.         print(“Select any one of the fab operation you want to do::”)  
    72.         print(“1. To list all directories which are present.”)  
    73.         print(“2. To create a new directory.”)  
    74.         print(“3. To move to another directory.”)  
    75.         print(“4. To create files in a specific directory.”)  
    76.         print(“5. To list all the files inside a directory.”)  
    77.         print(“6. To display the files and dirs in tree mode.”)  
    78.         print(“7. To exit from the code execution.”)  
    79.         menu_choice = input()  
    80.         menu_choice = int(menu_choice)  
    81.   
    82.         if menu_choice == 1:  
    83.             callable = globals()[‘listAllDirs’]  
    84.             callable()  
    85.         elif menu_choice == 2:  
    86.             callable = globals()[‘createWorkingDir’]  
    87.             callable()  
    88.         elif menu_choice == 3:  
    89.             callable = globals()[‘moveToDir’]  
    90.             callable()  
    91.         elif menu_choice == 4:  
    92.             callable = globals()[‘createFiles’]  
    93.             callable()  
    94.         elif menu_choice == 5:  
    95.             callable = globals()[‘listFilesInDir’]  
    96.             callable()  
    97.         elif menu_choice == 6:  
    98.             callable = globals()[‘listAllDirsAndFilesInTreeMode’]  
    99.             callable()  
    100.         elif menu_choice == 7:  
    101.             sys.exit()  
    102.   
    103.           
    104.         print(“To move ahead with code execution enter [y] else [n]”)  
    105.         continue_or_exit = input()  
    106.   
    107.         if continue_or_exit == ‘y’ or continue_or_exit == ‘Y’:  
    108.             pass  
    109.         elif continue_or_exit == ‘n’ or continue_or_exit == ‘N’:  
    110.             sys.exit()  
    111.   
    112.   
    113. #the main fucntion is called to start the execution of the code.  
    114. if __name__ == ‘__main__’:  
    115.     main()  

    Output:

    nirnay@superbook:~$ python3 fabfile.py 
    Select any one of the fab operations you want to do::
    1. To list all directories which are present.
    2. To create a new directory.
    3. To move to another directory.
    4. To create files in a specific directory.
    5. To list all the files inside a directory.
    6. To display the files and dirs in tree mode.
    7. To exit from the code execution.
    1
    primary
    All dirs listed successfully.
    To move ahead with code execution enter [y] else [n]
    y
    Select any one of the fab operations you want to do::
    1. To list all directories which are present.
    2. To create a new directory.
    3. To move to another directory.
    4. To create files in a specific directory.
    5. To list all the files inside a directory.
    6. To display the files and dirs in tree mode.
    7. To exit from the code execution.
    2
    Enter the name of the directory that you want to create
    mydir
    mydir directory created successfully.
    To move ahead with code execution enter [y] else [n]
    y
    Select any one of the fab operations you want to do::
    1. To list all directories which are present.
    2. To create a new directory.
    3. To move to another directory.
    4. To create files in a specific directory.
    5. To list all the files inside a directory.
    6. To display the files and dirs in tree mode.
    7. To exit from the code execution.
    1
    mydir
    primary
    All dirs listed successfully.
    To move ahead with code execution enter [y] else [n]
    y
    Select any one of the fab operations you want to do::
    1. To list all directories which are present.
    2. To create a new directory.
    3. To move to another directory.
    4. To create files in a specific directory.
    5. To list all the files inside a directory.
    6. To display the files and dirs in tree mode.
    7. To exit from the code execution.
    3
    Enter the name of the directory to which you want to move
    mydir
    /home/client/Desktop/mydir
    directory changed successfully
    To move ahead with code execution enter [y] else [n]
    y
    Select any one of the fab operations you want to do::
    1. To list all directories which are present.
    2. To create a new directory.
    3. To move to another directory.
    4. To create files in a specific directory.
    5. To list all the files inside a directory.
    6. To display the files and dirs in tree mode.
    7. To exit from the code execution.
    4
    Enter the name of the directory in which you want to create files
    mydir
    Files were created successfully in the media directory.
    To move ahead with code execution enter [y] else [n]
    y
    Select any one of the fab operations you want to do::
    1. To list all directories which are present.
    2. To create a new directory.
    3. To move to another directory.
    4. To create files in a specific directory.
    5. To list all the files inside a directory.
    6. To display the files and dirs in tree mode.
    7. To exit from the code execution.
    5
    Enter the name of the directory in which you want to list files
    mydir
    files1
    files10
    files11
    files12
    files13
    files14
    files15
    files2
    files3
    files4
    files5
    files6
    files7
    files8
    files9
    Files are listed successfully in the mydir directory.
    To move ahead with code execution enter [y] else [n]
    y
    Select any one of the fab operations you want to do::
    1. To list all directories which are present.
    2. To create a new directory.
    3. To move to another directory.
    4. To create files in a specific directory.
    5. To list all the files inside a directory.
    6. To display the files and dirs in tree mode.
    7. To exit from the code execution.
    6
    .
    |-- mydir
    |   |-- files1
    |   |-- files10
    |   |-- files11
    |   |-- files12
    |   |-- files13
    |   |-- files14
    |   |-- files15
    |   |-- files2
    |   |-- files3
    |   |-- files4
    |   |-- files5
    |   |-- files6
    |   |-- files7
    |   |-- files8
    |   `-- files9
    `-- primary
    
    2 directories, 15 files
    All dirs and files are listed successfully.
    To move ahead with code execution enter [y] else [n]
    n
    

    When a particular operation is triggered on the client machine, a secure connection is established between the remote site server and the client machine. After the successful establishment of the connection between the remote site server and the client machine with the help of the fabric function, we have used the above-written code to perform various operations on the remote site server using the fabric module of Python. These corporations were initiated from the client machine. The various operations that are carried out include changing the current working directory of the code execution, creating a new directory, listing all the files that are present in a particular directory, creating new files a set of new files inside a directory, listing all the files and directories that are present inside a particular directory in a recursive manner, which means the files or directories I In addition, separate functions have been written for each of these operations so that they can carry out the action that has been specified. In each method, a secure connection between the client machine and the server is initially established. The inbuilt functions of the fabric module are utilised in order to successfully establish the secure connection between the server and the client. After the connection has been successfully established, the method’s designated operation is carried out. Once the user has entered the name of the directory that needs to be created, the create directory operation is carried out. Once the user has entered the name of the directory that needs to be created, the create directory operation is carried out. Once the directory is successfully created, a similar message is prompted to the user. For instance, if the user has selected to create a new directory inside a specific directory, the user will be prompted to enter the name of the new directory that he wants to create. Similarly, if the user chooses the option to list all of the directories that are contained within a specific directory, they will be prompted to enter the name of the directory from which we want to list the children directories. Once the user has entered the name of the parent directory, all of the directories that are contained within the directory will be listed. In a similar vein, irrespective of which option the user chooses, they will be prompted to provide the pertinent input in the event that doing so is necessary, the user’s chosen operation will then be carried out on the server, and the user will be shown the result of the operation in the form of output. The user is presented with a number of functions or options, each of which represents a method for carrying out a specific operation on the remote site server. The user is able to select any one of these options in order to carry out the operation in question. This options menu is continually printed in order to carry out a number of different options. If the user wants to abort the execution of the current code, he can choose the final option, which will allow him to do so with the assistance of which he can abort the execution of the current code.

    Fabric Module in Python Offers the Following Benefits:

    Now that we have that out of the way, let’s talk about some of the major benefits of the Fabric Module in Python that make it a very powerful and popular choice among the developers for automating a list of tasks that needs to be done repeatedly on the remote server that are prerequisites for various configurations of the applications. These are the advantages that make the Fabric Module in Python a very powerful and popular choice among the developers.

    • Given that Fabric is a Python library, any Python command (or method) and module can be used with it out of the box. Fabric’s main value is its vast and superb interaction with SSH, which allows you to automate everything with simple scripts (i.e. fabfile.py). This section contains a list of Fabric tools (such as functions) that may be used to interface with environments where commands you express are executed.
    • Deploying an application (whether it’s a website, an API, or a server) usually entails starting from scratch (or from a snapshot), updating everything, downloading dependencies, setting up the file structure and permissions, and finally uploading your codebase – or downloading it using a version control system like Git. You’ll probably have instructions that need to be run regularly during the development phase (ex: right before entering a deployment cycle).
    • Being able to script these processes (both local and remote) in a logically ordered and – most importantly – programmable manner quickly becomes beneficial once you realize how much time is wasted repeatedly repeating the same steps, making everything error-prone in the process. Fabric comes to your rescue in the shape of a Python file that knows exactly what to do and where to do it.
    • Things that appear mysterious will rapidly become familiar once you start working with your droplet (which is a fully virtualized server with complete management and access). It’s only natural to expect some challenges as you launch your applications and begin dealing with their maintenance. However, as your application becomes more popular and things begin to expand, the necessity to manage several droplets and repeat everything ceases to be enjoyable.
    • A single Fabric script (fabfile), as we indicated in the beginning, can be used to conduct activities on both the local machine and the distant system (s). Fabric offers the local operative the ability to run commands locally for this purpose.
    • However, unlike run or sudo, there is no ability to interact with the output of local in the same way. The switch can be configured with the capture argument to capture or print either output. Local helpers, such as the lcd context manager (which sets the local working directory), are honored in the same manner as run (or sudo) honors the cd context manager.

    So far in this article, we have seen how we can use the fabric module in Python to connect to a remote server and perform various operations on that remote server. The primary use case of the fabric module is seen in the scenarios where a system administrator or network controller needs to manage several client machines having different configurations and requirements throughout the organisation. In this scenario, the network administrator for this system administrator can use the fabric module to connect to the remote server. In a similar vein, in this example, we saw how we can easily carry out a variety of operations on the server that is located at a remote site with the assistance of a straightforward Python script. These capabilities allow these functions to perform simple to complex tasks with equal ease.

    Fabric Module in Python Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticlePython fStrings Quiz
    Next Article Encapsulation in Python

    Related Posts

    python

    Plot With Pandas Python Data Visualization Basics

    March 27, 2023
    python

    Defining and Calling Python Functions

    March 27, 2023
    python

    BreadthFirst Search in Python

    March 27, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.