Wednesday, July 1, 2009

Script SSH commands

Anyone who has ever done Linux or Unix scripting has probably run across the problem of sending commands to a remote host inside a script. Well it turns out the trick to accomplishing this is to append the commands as a string at the end of the SSH connection command, like this:
ssh [user]@[server] "[command]"
For example, if you wanted to connect to a server at 192.168.1.100 with the username "james" and list the contents of that user's home directory, you would use this syntax:
ssh james@192.168.1.100 "ls ~/"
You can also chain multiple commands together. For example, if you wanted to list the contents of the home directory and print the contents all all files with the ".txt" extension, it would look like this:
ssh james@192.168.1.100 "ls ~/ ; cat *.txt"
This can also be used to execute scripts on the server. For example, if you wanted to send a script to the server and then run it, you would enter these commands:
scp my-script.sh james@192.168.1.100:~/my-script.sh
ssh james@192.168.1.100 "chmod +x ~/my-script.sh ; ~/my-script.sh"

No comments:

Post a Comment