Create alias for ssh connecting
I'd like to speed up connecting to specific servers.
I have the servers let's say:
123.123.123.1
123.123.123.2
123.123.123.3
I normally connect with the following:
ssh -p 12345 [email protected]
This is a pain because the only difference between the servers is the last number of the ip.
I tried the following code:
alias ssht='{ ip=$(cat -); ssh -p 12345 my_user@"123.123.123.$ip"; }<<<'
However I get an error:
karl@karls-laptop ~/scripts $ ssht 1
Pseudo-terminal will not be allocated because stdin is not a terminal.
Is there a way to get this working?
Use the intended way and write the options and aliases into ~/.ssh/config
:
Host 1
Port 12345
User my_user
HostName 123.123.123.1
Host 2
Port 12345
User my_user
HostName 123.123.123.2
and so on...
And then connect just using
ssh 1
ssh 2
...
This calls for a function -- simple and robust, whereas an alias
in this case would be fragile.
Something like this should do:
function ssht () {
[[ $1 =~ ^(1|2|3)$ ]] || { echo 'Not a valid last octet value !!' && return ;}
ip=123.123.123.$1
ssh my_user@"$ip" -p 12345
}
The condition [[ $1 =~ ^(1|2|3)$ ]]
makes sure you have entered one of 1, 2, 3 as first argument (any trailing argument is ignored).
Now, you can give the desired last octet as the first argument:
ssht 1
ssht 2
ssht 3
Put this in your ~/.bashrc
for having it available in any interactive session.