【问题标题】:Executing sudo command with space through python通过python执行带空格的sudo命令
【发布时间】:2013-04-03 12:49:46
【问题描述】:

大家好,我有问题。

我正在执行一个需要运行 sudo 命令才能继续的 python 脚本。这是命令:

sudo /etc/init.d/test restart

问题是,无论我如何执行它,它只会运行 sudo 和 /etc/init.d/test 并返回:

sudo: /etc/init.d/test: command not found

问题似乎是重新启动没有与命令一起发送。

这些是我尝试运行命令的方式:

使用操作系统尝试1

os.system('sudo /etc/init.d/test restart')

使用子进程尝试 2

x = subprocess.Popen(['sudo','/etc/init.d/test','restart'])
x.communicate()

尝试 3 再次使用子进程

x = subprocess.Popen(['sudo','/etc/init.d/test restart'])
x.communicate()

这实际上返回了:

sudo: /etc/init.d/test restart: command not found

这没有任何意义,因为如果我直接在系统上执行命令,它就可以工作。
关于如何做到这一点的任何想法?

【问题讨论】:

  • 差不多,但那里给出的答案对我不起作用。正如你所看到的,给出了完整的路径,但它仍然不起作用:(我应该在那个线程中再次问这个问题吗?如果是这样,我很抱歉我想,因为它没有回答我,我可以再问一次。跨度>
  • sudo 命令将为您提供 root 权限,并且需要您的密码才能执行此操作。在没有密码的情况下授予 root 访问权限是一个非常非常糟糕的主意
  • 这将在一堆具有不同密码的机器上工作,所以我认为最好让用户输入密码。

标签: python python-2.7


【解决方案1】:
#!/usr/bin/env python
import subprocess,getpass
password = getpass.getpass()
#proc = subprocess.Popen(
#  ['sudo','-p','','-S','/etc/init.d/test','restart'],
#   stdin=subprocess.PIPE)
proc = subprocess.Popen(
    ['sudo','-p','','-S','echo','restart'],
    stdin=subprocess.PIPE)
proc.stdin.write(password+'\n')
proc.stdin.close()
proc.wait()

【讨论】:

  • 当我执行此操作时,没有任何反应,稍后脚本会继续。现在因为这应该重新启动系统,所以我不确定它是否有效。假设只是一个空白屏幕还是会出现错误?
  • 脚本只是提示输入密码并打印单词'restart'。我试过了,它对我有用。
【解决方案2】:

如果你得到这个:

sudo: /etc/init.d/test: command not found

它表示 /etc/init.d/test 不存在。从命令行自己尝试一下:

> sudo blarg whatever whatever
sudo: blarg: command not found

因此,只需确保您尝试执行的命令确实存在:

ls -l /etc/init.d/test

如果您仍然有问题,请尝试通过首先执行“sudo whoami”来简化事情——一旦您开始工作,将其更改为您的“真实”命令。

【讨论】:

  • 是的,但我只知道它,因为它没有运行完整的命令 /etc/init.d/test restart。如果我要在 linux 控制台中运行完整的命令,它就可以工作。不过感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 2019-02-01
  • 2017-12-04
  • 2017-06-14
  • 1970-01-01
相关资源
最近更新 更多