Score:0

command subsitution doesn't work when issued from ssh

km flag

I have an Ubuntu vps to which I connect from my laptop that also runs Ubuntu.

When I ssh root@server to my server I can successfully run the following command:

root@server:~# wg set wg0 peer $(cat /etc/wireguard/clients/guard001_pub) remove

but when I do not want to login and just want to run the command remotely I get a permission denied error which I do not understand why. Because the file owned by root and has all rwx permissions.

username@mymachine:~$ ssh root@server "wg set wg0 peer $(cat /etc/wireguard/clients/guard001_pub) remove"

gives the following error:

cat: /etc/wireguard/clients/guard001_pub: Permission denied
Key is not the correct length or format: `remove'

Can anyone tell why is this happening and what is the best workaround?

Score:0
hr flag

Because you surrounded the command with double quotes, $(cat /etc/wireguard/clients/guard001_pub) gets evaluated by your local shell, before the ssh command is run.

Since the local cat /etc/wireguard/clients/guard001_pub fails, the local command substitution results in an empty string, and the remote command becomes

wg set wg0 peer remove

so that remove gets passed as the key.

Instead, use single quotes:

ssh root@server 'wg set wg0 peer $(cat /etc/wireguard/clients/guard001_pub) remove'

or perhaps better

ssh root@server 'wg set wg0 peer "$(cat /etc/wireguard/clients/guard001_pub)" remove'
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.