运行 python 以 sudo 用户身份在远程机器中执行脚本

Run python script in a remote machines as a sudo user

我对 python 编程还很陌生,作为我学习的一部分,我决定开始为一个简单的日常任务编写代码,这样可以节省一些时间,我已经完成了大部分脚本,但现在我看到执行它的巨大挑战,因为我需要在具有 sudo 用户访问权限的远程服务器上执行它。基本上我需要的是,

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.

感谢大家的回答。 Fabric 对我有用,下面是代码片段。

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

但在使用之前,请确保您已在主机中设置 sudo 访问权限,如下所示 (runcommand_user) NOPASSWD: ALL

你可以登录到主机并执行'sudo -l'来检查你是否有上面提到的访问权限

另一种方法是使用如下的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')