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 with the username "james" and list the contents of that user's home directory, you would use this syntax:
ssh james@ "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@ "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 james@
ssh james@ "chmod +x ~/ ; ~/"

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.