0

I found out that if you want to execute a command as superuser you need to add the following: echo <password> | sudo -s <command> .

First I wanted to suspend the Linux server with echo <password> | sudo -s pm-suspend, and it worked fine. Now I want to execute the command echo -e "\xff\x01\x00" > /dev/ttyUSB0

echo <password> | sudo -s echo -e "\xff\x01\x00" > /dev/ttyUSB0 does not work, I guess because of the ">" in it. What changes are needed to get the command working?

lasbr
  • 79
  • 1
  • 8

1 Answers1

0

First, never use echo password | .... on the command line. This is insecure as the password would remain in the history file, plus other users can see the password using the ps command. If you want to execute a sudo command without entering a password you can use the NOPASSWD option in /etc/sudoers. Check this: https://unix.stackexchange.com/questions/18830/how-to-run-a-specific-program-as-root-without-a-password-prompt


About the permission problem. You are right, the problem is the output redirection >. You need to know that the shell will open the output file, not the command running with sudo.

In this example:

sudo command > output.file

the shell tries to open output.file, then starts sudo command and set it's standard output to the open file. However, the shell does not have root permissions.

A workaround could be to use the tee command, like this:

command | sudo tee output.file

however, I would simply grant proper permissions to edit that file. On example way could be to create a group, change the group ownership of that file and you into that group. For example:

# Add group
sudo groupadd developers

# Change group ownership of the file
sudo chown root:developers output.file

# make the file writable by the group
sudo chmod g+w output.file

# Finally put you into that group
sudo usermod -a -G developers YOU

But if you are an admistrative user, meaning you can execute every command with sudo, the tee solution above is good enough.

Community
  • 1
  • 1
hek2mgl
  • 152,036
  • 28
  • 249
  • 266