Search code examples
linuxsshsu

Backticks with su -c in SSH Command without running command in it


I have a little question:

I want to echo something in the Crontab an several Servers, with Backticks. Heres my sample command:

for server in $( cat list ); do ssh -t $user@$server "su -c \"echo '35 * * * * $script_that_runs ''\'\`/bin/hostname\`''\'  $Parameter2 $Parameter3' >> /var/spool/cron/crontabs/root \" "; done

On the Remoteserver it shows up like:

35 * * * * $script_that_runs '$hostname'  $Parameter2 $Parameter3

But i want it that way:

35 * * * * $script_that_runs `/bin/hostname`  $Parameter2 $Parameter3

I havent found an answer yet. Maybe im just to silly atm to find one. Has anybody got an solution for this?

Problems were:

  • if i run su -c with single quotes, it won't work
  • if im not escaping the echo command every file in the actual directory will be echo'd in the crontab.

Command with best result:

for server in $( echo $servername ); do ssh -t $user@$server "su -c \"echo '35 * * * * /usr/lib/nagios/plugins/nsca_wrapper \`\`/bin/hostname\`\`  apt-check /usr/lib/nagios/plugins/check_apt' >> /var/spool/cron/crontabs/root \" "; done

Solution

  • You should double-escape the

    `
    

    character like this

    \\\`
    

    Example with minimal code:

     $ ssh -t host "su -c \"echo 'something \\\`/bin/hostname\\\`' > /tmp/test \"; cat /tmp/test ";
     something `/bin/hostname`