简体   繁体   English

以sudo用户身份在远程计算机上运行python脚本

[英]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. 我对python编程很陌生,作为学习的一部分,我决定开始为一个简单的日常任务编写代码,这将节省一些时间,我已经完成了大部分脚本,但是现在我看到了执行它的巨大挑战,因为我需要使用sudo用户访问权限执行远程服务器。 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. 运行sudo su-用户(不需要密码,因为它是基于SSH密钥的登录名)运行代码。 logout with the result assigned to varible. 注销并将结果分配给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. Fabric为我工作,下面是代码片段。

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 但是在使用此功能之前,请确保已在主机(runco​​mmand_user)主机中设置了如下的sudo访问权限:NOPASSWD:ALL

u can login into host and execute 'sudo -l' to check if you have the access as mentioned above 您可以登录主机并执行'sudo -l'来检查您是否具有上述访问权限

The other way is to use paramiko as below. 另一种方法是使用paramiko如下。

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') un_con = paramiko.SSHClient()un_con.set_missing_host_key_policy(paramiko.AutoAddPolicy())un_con.connect(主机,用户名=用户,key_filename = keyfile)stdin,stdout,stderr = un_con.exec_command(sudo -H -u sudo_user bash -c '命令')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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