简体   繁体   中英

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.

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

The other way is to use paramiko as below.

un_con=paramiko.SSHClient() un_con.set_missing_host_key_policy(paramiko.AutoAddPolicy()) un_con.connect(host,username=user,key_filename=keyfile) stdin, stdout, stderr = un_con.exec_command(sudo -H -u sudo_user bash -c 'command')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM