简体   繁体   English

无法在 python 脚本中执行 sudo 命令

[英]Unable to execute sudo command in python script

I am attempting to execute sudo from a python script:我正在尝试从 python 脚本执行 sudo:

import os
command = 'id'
os.popen("sudo -S %s"%(command), 'w').write('password')

My server is configured to not allow non-TTY shells to execute sudo for security reasons, is there a workaround for this to execute the sudo command using python (without using su).出于安全原因,我的服务器配置为不允许非 TTY shell 执行 sudo,是否有解决方法可以使用 python(不使用 su)执行 sudo 命令。

The above code outputs:上面的代码输出:

sudo: sorry, you must have a tty to run sudo

Based on this: https://stackoverflow.com/a/21444480/1216776 you should be able to do:基于此: https://stackoverflow.com/a/21444480/1216776你应该能够做到:

import os
import pty
command = 'id'

scmd ="sudo -S %s"%(command)

def reader(fd):
  return os.read(fd)

def writer(fd):
    yield 'password'
    yield ''

pty.spawn(scmd, reader, writer)

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

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