无法访问/dev/mem.尝试在 Raspberry Pi 上以 root 身份运行 [英] No access to /dev/mem. Try running as root on Raspberry Pi

查看:122
本文介绍了无法访问/dev/mem.尝试在 Raspberry Pi 上以 root 身份运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是树莓派的菜鸟.我已经完成了所有设置,我正在尝试使用 shell_exec 通过浏览器运行文件.

I am a Noob with the raspberry pi. I have it all setup and I am trying to run a file via the browser using shell_exec.

这里是python文件的内容:

Here is the content of the python file:

#! /usr/bin/python

import time
import RPi.GPIO as GPIO

PIN_17 = 17 # Define LED colour and their GPIO pin
GPIO.setmode(GPIO.BCM)

GPIO.setup(PIN_17, GPIO.OUT) # Setup GPIO pin

GPIO.output(PIN_17, True)  #Turn on
time.sleep (1)               #Wait
GPIO.output(PIN_17, False) #Turn off

GPIO.cleanup() #Useful to clear the board

我在目录 /home/pi/ 中有名为 trigger_pin.py

I have the file in the directory /home/pi/ called trigger_pin.py

我正在尝试使用 remote.php 中的以下 PHP 命令通过浏览器运行文件:

I am trying to run the file through the browser using the PHP command below in remote.php:

<?php
$output = shell_exec("cd /home/pi/ && ./trigger_pin.py 2>&1"); //run command
echo "$output"; //output from command
?>

我得到的输出是:

回溯(最近一次调用最后一次):文件./trigger_pin.py",第 9 行,在 GPIO.setup(PIN_17, GPIO.OUT) # 设置 GPIO 引脚运行时错误:无法访问/dev/mem.尝试以 root 身份运行!

Traceback (most recent call last): File "./trigger_pin.py", line 9, in GPIO.setup(PIN_17, GPIO.OUT) # Setup GPIO pin RuntimeError: No access to /dev/mem. Try running as root!

推荐答案

默认情况下,Raspberry Pi 的 GPIO 接口需要超级用户(root")权限.您可能打开了一个 root 用户 shell,因此在命令行中执行您的 Python 脚本不会出现问题.然而,您的 PHP 应用程序服务器可能正在以其他用户身份运行.

By default, the Raspberry Pi's GPIO interface requires superuser ("root") permissions. You may have a root-user shell open, therefore executing your Python script works without issues from the command line. Whereas, your PHP application server is likely running as another user.

最直接的解决方案是将 PHP 应用服务器的用户(例如,www-data)添加到 /etc/sudoers,这将创建一个特权用户.

The most straight-forward solution is to add the PHP application server's user (e.g., www-data) to /etc/sudoers, which will create a privileged user.

www-data  ALL = NOPASSWD: ALL

然后使用 sudo 提升您的权限:

And then escalate your permissions with sudo:

shell_exec("cd /home/pi/ && sudo ./trigger_pin.py 2>&1");

如果您这样做,请务必确保您验证了您的 Web 服务器可以执行的内容的安全性(即,不要在查看源代码的情况下盲目安装 Web 脚本).

或者,您可以重构 Python 脚本以使用 pigpiopigpiod 守护进程,它以超级用户权限运行(因此您的应用程序不必这样做).或者您可以使用使用 setuid 以 root 身份运行的单独工具,例如 Quick2Wire 的 GPIO 管理员.

Alternatively, you can refactor your Python script to use pigpio's pigpiod daemon, which runs with superuser privileges (so your application doesn't have to). Or you can use a separate tool that uses setuid to run as root such as Quick2Wire's GPIO Admin.

您还可以在 Raspberry Pi Stack Exchange 中找到更多帮助.

You can also find more help at Raspberry Pi Stack Exchange.

这篇关于无法访问/dev/mem.尝试在 Raspberry Pi 上以 root 身份运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆