SSH Scripting – How to Echo or Paste Commands into SSH Terminal with Shell Script

bashcommand linescriptsssh

I've been having an issue lately trying to figure out how to get my shell script to paste a command into a ssh terminal after automatically logging into an ssh terminal. I am trying to setup a cron tab that will execute my shell script that automatically logs into an ssh terminal for my Ubiquiti access point and inserts a command to turn the LED off at a certain time. So far I've been able to automatically SSH into the access point when I run the shell script but when it logs in it doesn't paste the command. After I manually exit the SSH terminal, the echo command runs and put the command in after leaving the terminal. I was wondering if anyone could help me figure this out. I've been looking everywhere but can't find any answers. Thank you ahead of time. This is the code I have currently in my shell script. The command I want to be able to run in the SSH terminal is ("mgmt.led_pattern_override=2" >> /var/etc/persistent/cfg/mgmt)

   #!/bin/sh
sshpass -p "password" ssh -o StrictHostKeyChecking=no username@192.168.1.3;
   echo '"mgmt.led_pattern_override=2" >> /var/etc/persistent/cfg/mgmt';
exit

Best Answer

Instead of starting an interactive ssh session, pass the echo command directly as an argument to ssh:

sshpass -p "password" ssh -o StrictHostKeyChecking=no username@192.168.1.3 '
   echo "mgmt.led_pattern_override=2" >> /var/etc/persistent/cfg/mgmt
'

Your other option would be to use expect to script the interactive session - but that's overcomplicated for this case.

Related Question