简体   繁体   English

Python在sudo中调用bash脚本的子进程

[英]Python calling subprocess of a bash script in sudo

I'm running a python script on my rPi. 我在rPi上运行python脚本。 I have to run it in sudo to use the rpi.gpio library, but when I do, it won't let me run my bash script in non-sudo. 我必须在sudo中运行它才能使用rpi.gpio库,但是当我这样做时,它不会让我在非sudo中运行我的bash脚本。 This causes my ssh commands to prompt for passwords, even though the key-gen authentication is set. 即使设置了密钥生成身份验证,这也会导致我的ssh命令提示输入密码。

I'm sure I'm missing something simple. 我确定我缺少一些简单的东西。 Can anyone help? 有人可以帮忙吗?

Running python script: 运行python脚本:

sudo python ./runcam.py

In the py script I'm running this: 在py脚本中,我正在运行以下命令:

subprocess.call("./runit", shell=True)

And my ssh script: 而我的ssh脚本:

#!/bin/bash

      FNAME=`date +'%H-%M-%S-%m%d%Y'`

      ssh pi@192.168.0.8 '
        mkdir $FNAME
      ' & 

      ssh pi@192.168.0.9 '
        mkdir $FNAME
      ' & 

You can also drop your root permissions with sudo. 您也可以使用sudo删除您的root权限。 You just need to check for user id 0, and the environment variable "SUDO_USER", then sudo -u "$SUDO_USER" command . 您只需要检查用户ID 0和环境变量“ SUDO_USER”,然后检查sudo -u "$SUDO_USER" command

You can do it in your bash script like this: 您可以在bash脚本中执行以下操作:

# if we're root from sudo, run this script as the original user instead
[[ "$(id -u)" = "0" && -n "${SUDO_USER:-}" ]] && exec sudo -u "$SUDO_USER" "$0" "$@"

Full script example: 完整脚本示例:

#!/bin/bash -u
[[ "$(id -u)" = "0" && -n "${SUDO_USER:-}" ]] && exec sudo -u "$SUDO_USER" "$0" "$@"
id -u

This script will print your user id, regardless of whether it's run with sudo. 无论是否与sudo一起运行,此脚本都会打印您的用户ID。

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

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