You should combine two related Ask Ubuntu answers, one for logging into SSH via specific port and one for running commands on remote server , into one script. Of course, you'd need to have some form of data-structure to hold server+port correspondence. That could be either bash associative arrays or with POSIX shell script - a case statement. Assuming your username on all hosts is the same, we could come up with something like this:
#!/bin/sh
# bar host has ssh server on port 22, while baz - on port 2222
host_port(){
case "$1" in
"bar") echo 22 ;;
"baz") echo 2222 ;;
esac
}
# set positional parameters of script to hosts and iterate over them
set -- bar baz
for host ; do
# command substitution will call function,
# function's return value will be the port number
ssh ssh://username@"$host":"$(host_port "$host")" -t "systemctl stop tomcat"
done
Now, a giant disclaimer: This is just an example. I don't have 6 servers to test the script, so adapt it to your needs as necessary. If you have different usernames on each host, use another case
statement
Side note on logging in: if you have private key, which is accepted by all 6 servers it will be easy to log-in just by adding -i ~/.ssh/id_rsa
. Alternative to that would be to create a ~/.ssh/config
file with key/password information for each host. This is described in Lekensteyn's answer. If you're not familiar with SSH keys (and I understand it's kinda confusing topic), you might wanna read ssh.com article on the topic.