Aug 292012

This is another post that is more for me than the general public, to help me remember some Bash scripting commands.


Script  Trick 1 – Remote Command Execution Over SSH

Many times while administering Linux systems or during an investigation I have found it necessary to issue a command on a remote system while logged into another system.  The reasons for this are many (not just commands, but entire scripts can be executed from a centralized server of some sort).  Below are some examples how to accomplish this feat.


ssh newton01 "sudo chown -R wwhitman:wwhitman /opt/appdir"

If keys have been exchanged between the host from which this entire command was issued and the host that we’re attempting to SSH into, then the above command will not ask for a password, which is ideal if the above command is embedded in a script.  If keys have not been exchanged, a password will be required and this command must be issued in an interactive session (i.e. not while embedded in a script to be run from cron or some other automated process).


So, what this command does is SSH into a remote host named “newton01” and assumes that we are the same user as the one from which the entire command was issued (local host user).  It will then sudo, assuming escalated privileges on “newton01” as provided in the /etc/sudoers file, and then perform the chown command on “newton01” to change the owner and group of the /opt/appdir directory to wwhitman.


Here’s another command that’s similar to the previous one, except there’s some redirection occurring.


ssh newton01 'sudo bash -s' < /opt/remotescripts/app.check

This command SSHs into “newton01” and then using sudo again, it escalates its bash shell privileges to run the script found on the local host at the directory /opt/remotescripts/app.check. In other words, it takes the script app.check from the local host, shovels it over to “newton01” and runs it while on “newton01”.  

Here are a couple more examples. No explanations are provided.  The SCP examples are there to help me remember the two different ways of moving files.  The first one moves all files on “newton01” from /home/wwhitman/tmp to the local server in the current directory.  The second SCP command shows how to move a file called foo to “newton01”.

ssh newton01 "pwd; ls -la"

ssh newton01 "sudo rm -rf tmp"

scp newton01:/home/wwhitman/tmp/* .

scp ./foo newton01:/wwhitman/tmp/