Sudo Permission cat, echo at root folder

Hello, I’m trying to understand why I don’t have full permission by using echo and cat.
I have here a some version of command where only version 3 works, can someone explain to me why the other don’t work?

I’m in the wheel group and I add my self to the sudoers file…

Version 1

if [[ -f /etc/fail2ban/jail.local ]]; then
        sudo cat >/etc/fail2ban/jail.local <<<"

    [DEFAULT]
    bantime = 1d
    [sshd]
    enabled = true"
    fi

Version 2

    if [[ ! -f /etc/fail2ban/jail.local ]]; then
        sudo echo -e "\n[DEFAULT]\nbantime = 1d\n[sshd]\nenabled = true\n" >/etc/fail2ban/jail.local
    fi

Version 3

    if [[ ! -f /etc/fail2ban/jail.local ]]; then
        print '\n[DEFAULT]\nbantime = 1d\n[sshd]\nenabled = true' | sudo tee /etc/fail2ban/jail.local
    fi

Version 4 / 5

sudo cat <<<'EOF' >>/etc/fail2ban/jail.local
    test
    EOF

    sudo cat >/etc/fail2ban/jail.local <<<'
    test2
    '

The simple explanation is that cat and echo are two different commands.

But perhaps I don’t understand the question.

Your scripts need to run as root - or you could print out the commandline using delimiters

When you run sudo with a command, only the command and parameters are privileged. A pipe transfers data from one command to another command, e.g. |, < or >.

Works:

print 'root' | sudo tee /etc/config
sudo sh -c 'echo "root" >/etc/config'
2 Likes

So to have it work for echo and cat there have to be ‘sh -c’ added to it. Thank you

cat

ff() {
    sudo sh -c 'cat >/etc/config <<<" cat

    1
    2
    3"'
}

echo

fff() {
    sudo sh -c 'echo "echo

    1
    2
    3" >/etc/config'
}

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.