FrankDrebbin
FrankDrebbin

Reputation: 135

Reading a file as sudo from Ruby on Rails

Surprisingly i did not find anyone trying to do this, that's why im making this question.

Thing is i have a file, where im storing some data. I want to have an option in my rails project, where you can "export" some objects that are defined in this file.

This file belongs to root, soo if i try to read it with File.read("myfile.json") it fails with this error:

#<Errno::EACCES: Permission denied @ rb_sysopen - /opt/rb/etc/cep/state.json>

Is there a way i can read it as root? Maybe the solution is to run a "sudo cat myfile.json" as a command from ruby and inject the result into a variable?

My goal is to place the contents of this file inside another one that the user will download, so later he can upload this file and have all the objects from before. It was weird not seeing more people trying to do this so I don't know if maybe i'm asking something stupid. I found none information in google about this, maybe is not possible to open a file as sudo with File.open.

Upvotes: 2

Views: 606

Answers (2)

Ebordon
Ebordon

Reputation: 31

If you want to access a file, I think it's not a good idea to give your application sudo access. It is potentially dangerous.

You might change the permission on the file instead, by changing the owner/group for the file.

Here you can find how to get the user running the application.

This command will change the owner of the file

sudo chown <my_user> /opt/rb/etc/cep/state.json

Another option is to create a group with the current owner and the rails user and set that group as owner:

sudo groupadd mynewgroup
sudo usermod -a -G mynewgroup <my_user>
sudo usermod -a -G mynewgroup <current_user>
sudo chgrp mynewgroup /opt/rb/etc/cep/state.json

Upvotes: 1

Vin&#237;cius Alonso
Vin&#237;cius Alonso

Reputation: 151

A simple way to quickly solve it is change the file's owner.

sudo chown $USER myfile.json

Upvotes: 1

Related Questions