Search code examples
pythonunixsudoremote-server

Run python script in a remote machines as a sudo user


I pretty new to python programming, as part of my learning i had decided to start coding for a simple daily task which would save sometime, I'm done with most part of the script but now i see a big challenge in executing it , because i need to execute it a remote server with the sudo user access. Basically what i need is,

login to remote system. run sudo su - user(no need of password as its a SSH key based login) run the code. logout with the result assigned to varible. I need the end result of the script stored in a variable so that i can use that back for verification.


Solution

  • Thanks for all the answers guys. Fabric worked for me, below is the code snippet.

    from fabric.context_managers import settings
    from fabric.api import *
    with settings(host_string='username@host',user='runcommand_user'):
         run('command')
    

    But before using this make sure you have set sudo access as below in the host (runcommand_user) NOPASSWD: ALL

    u can login into host and execute 'sudo -l' to check if you have the access as mentioned above