0

I want to change the static IP address for interface eth0 on my raspberry pi 4 from a web page. I am running buster lite 4.19 with no desktop. From what I understand, I need to modify the "static ip_address=" line in the /etc/dhcpcd.conf file to make the change permanent.

I can execute the following command and it works fine until I restart the controller.

ifconfig eth0 192.168.1.10 netmask 255.255.255.0

I found this link which works great from the command line. Using sed to change ip addresses in dhcpcd.conf file

I attempted to use the exec() command to execute the commands from the php script. The read works fine but the sed operation does not write anything. I am assuming a permissions issue but not sure how to overcome this. I am using the following commands in my code.

$newIPcidr = "192.168.1.10/24";

$cmd = "cat /etc/dhcpcd.conf | grep -e '^static ip_address=' | cut -d= -f2";
$curIP = exec($cmd);
 
$cmd = "sudo sed -i -e \"s@^static ip_address=" . $curIP . "\b@static ip_address=" . $newIPcidr . "@g\" /etc/dhcpcd.conf";
$output = exec($cmd);

Is there a better way to do this?

Thanks in advance for any help on this!

1 Answer 1

1

I think your problem is the generic one of executing a command as root when you are not root.

There are several ways around this:

1/. write a specific script or binary that executes as root.

2/. use sudo and ensure that the pi web identity (www-data) has an entry in the /etc/sudoers file to enable it to execute the command you specify as root, without using a password

3/. change the permissions on the file you want to e.g. group write and make its group www-data. Hmm. I see that mine is netdev. possibly safer then to give it 666 permissions so that its world writable, and leave the group the same.

I think for a quick hack in a protected environment the latter might be easiest. e.g sudo chmod 666 /etc/dhcpcd.conf and see if that works.

2/. is OK for reasonably secure environments.

I've used 1/. when I want all users to be able to execute something root-ish

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Leo, I will give this a try.
I decided to use option 2 and change group to www-data and add that user with sed access only to sudoers. Works great! I am not an expert in apache or linux security so what potential security issues did I just create for myself?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.