21

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 my_user@123.123.123.1

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?

5 Answers5

68

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
...
maloo
  • 105
Jakuje
  • 6,605
  • 7
  • 30
  • 37
  • 1
    I think OP is trying to connect automatically with something that takes taking one argument (last octet), not statically putting anything (this would be the best approach then). – heemayl Aug 02 '17 at 14:18
  • Hard to guess if it is request for dynamic or static aliases. But this is the standard way to simplify writing and even if it would be for dynamic, he can get rid of writing the port and the user already. Other answers already discuss home-brew possibilities how to do it with bash functions. – Jakuje Aug 02 '17 at 14:21
  • 1
    @Jakuje heemayl is correct. I need to be able to pass an argument. Otherwise this method would of been selected as the answer :) – Karl Morrison Aug 02 '17 at 14:43
  • 2
    You can still provide a ssh config line for Host 123.123.123.* that specifies the port and username! – Riking Aug 02 '17 at 17:32
  • @Riking Thanks for comment. Yes. Additionally, the IP will be autocompleted, so you will mostly end up writing just the last number. – Jakuje Aug 02 '17 at 18:50
  • @KarlMorrison You could always just create 255 hosts, h1 through h255, in the config file! ... but yeah, a function probably makes more sense :) – Dewi Morgan Aug 02 '17 at 20:52
  • or h1-N.somedomain dns entries, and properly set up resolv.conf – ivanivan Aug 03 '17 at 02:02
  • Thx! It make life much easier if you have multiple server! :-) – MartinTTS Mar 27 '24 at 12:31
19

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.

heemayl
  • 91,753
  • Very nice! However to make it complete, replace exit with return and include the user my_user. :) – Karl Morrison Aug 02 '17 at 14:30
  • @KarlMorrison Approved. – heemayl Aug 02 '17 at 14:38
  • 2
    "This calls for a function" I use the same rule-of-thumb, if parameters are involved, use a function instead of an alias. – Lasse Meyer Aug 02 '17 at 15:34
  • I like this answer, I think it will be even greater with some additional input handling octet=$1; [[ $octet =~ ^[0-9]+$ ]] && [[ $octet -lt 255 ]] && [[ $octet -gt 0 ]] && ssh -p <portNumber> user@hostname –  Aug 02 '17 at 16:42
  • 2
    While this works, it is overkill and not needed. Simply use the built-in ~/.ssh/config file – ivanivan Aug 03 '17 at 02:00
  • @ivanivan Yeah? How to implement the logic in ~/.shh/config? – heemayl Aug 03 '17 at 02:12
  • I don't see any need for a logic. what is the problem with typing ssh h1 ssh h2, ... ? – pLumo Aug 03 '17 at 07:26
  • @RoVo That comes afterwards; are you gonna put all the snippets for hosts individually inside ~/.ssh/config? Also, as per example only a limited number of hosts need to be matched, so only ?/* (ssh does not support character classes) would not get us the desired precision. Perhaps you should read the question carefully again. – heemayl Aug 03 '17 at 07:51
  • Why not "put all the snippets for hosts individually inside ~/.ssh/config". for i in $(seq 1 100); do printf "\nHost h$i\n Port 12345\n User my_user\n HostName 123.123.123.$i\n" >> ~/.ssh/config; done – pLumo Aug 03 '17 at 08:00
  • @RoVo Suit yourself with the definition of Overkill and Scalability. – heemayl Aug 03 '17 at 08:01
  • (1|2|3) == ([123]) – Avinash Raj Aug 04 '17 at 11:44
  • ([123]) == ([1-3]) – MTCoster Aug 04 '17 at 11:48
18

You can use patterns in ~/.ssh/config. From man ssh_config:

PATTERNS
     A pattern consists of zero or more non-whitespace characters, ‘*’ (a
     wildcard that matches zero or more characters), or ‘?’ (a wildcard that
     matches exactly one character).  For example, to specify a set of
     declarations for any host in the “.co.uk” set of domains, the following
     pattern could be used:

           Host *.co.uk

     The following pattern would match any host in the 192.168.0.[0-9] network
     range:

           Host 192.168.0.?

Combined with:

HostName
    Specifies the real host name to log into.  This can be used to
    specify nicknames or abbreviations for hosts.  If the hostname
    contains the character sequence ‘%h’, then this will be replaced
    with the host name specified on the command line (this is useful
    for manipulating unqualified names).  The character sequence ‘%%’
    will be replaced by a single ‘%’ character, which may be used
    when specifying IPv6 link-local addresses.

So, in your ~/.ssh/config, put:

Host ?
    Hostname 123.123.123.%h
    Port 12345
    User my_user

Then:

$ ssh -v 1
OpenSSH_7.4p1, LibreSSL 2.5.0
debug1: Reading configuration data /home/muru/.ssh/config
debug1: /home/muru/.ssh/config line 41: Applying options for ?
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to 123.123.123.1 [123.123.123.1] port 12345.
debug1: connect to address 123.123.123.1 port 12345: Connection refused
ssh: connect to host 123.123.123.1 port 12345: Connection refused
muru
  • 197,895
  • 55
  • 485
  • 740
7

Use a function instead :

function ssht(){
 ssh -p 12345 my_user@123.123.123.$1
}
$ ssht 1
$ ssht 2
$ ...

A better solution is to use a ssh config file:

touch ~/.ssh/config

with some lines similar to:

Host some-name
    HostName 123.123.123.1
    User your_user
    Port 22

You can also use ssh keys to improve the speed, finally you only run:

ssh some-name

and you are connected to that server.

Ravexina
  • 55,668
  • 25
  • 164
  • 183
3

You don't even need to use a name like ssht. Names starting with digits, even only digits are valid hostnames in ssh config file.

Below works on Xubuntu Xenial

Part of my ~/.ssh/config

Host 1
        Hostname bastion.example.me
        User said
        Port 22
        IdentityFile ~/.ssh/id_rsa
        ForwardAgent yes

Command I run (below I added -vv for verbose logging to STDOUT a.k.a your screen by default)

ssh -vv 1

Output

OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /home/said/.ssh/config
debug1: /home/said/.ssh/config line 24: Applying options for 1
debug1: /home/said/.ssh/config line 540: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "bastion.example.me" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to bastion.example.me [XXX.YYY.120.51] port 22.
debug1: Connection established.
debug1: identity file /home/said/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/said/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.2 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to bastion.example.me:22 as 'said'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:44tChrTUMwuRcOi6laiYlf6VM3qAD+PEn9EdNMribFw
debug1: Host 'bastion.example.me' is known and matches the ECDSA host key.
debug1: Found key in /home/said/.ssh/known_hosts:69
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug2: key: /home/said/.ssh/id_rsa (0x562c764294f0), explicit, agent
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/said/.ssh/id_rsa
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg rsa-sha2-512 blen 279
debug2: input_userauth_pk_ok: fp SHA256:KQNLYiJICyNbKmIxVVgc67RF+qRKjNi3w+0iXz/YDyk
debug1: Authentication succeeded (publickey).
Authenticated to bastion.example.me ([XXX.YYY.120.51]:22).
debug1: channel 0: new [client-session]
debug2: channel 0: send open
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug2: callback start
debug1: Requesting authentication agent forwarding.
debug2: channel 0: request auth-agent-req@openssh.com confirm 0
debug2: fd 3 setting TCP_NODELAY
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1
debug2: channel 0: request shell confirm 1
debug2: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug2: channel_input_status_confirm: type 99 id 0
debug2: PTY allocation request accepted on channel 0
debug2: channel 0: rcvd adjust 2097152
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0
Welcome to Ubuntu 16.04.2 LTS (GNU/Linux 4.8.0-42-lowlatency x86_64)
<TRUNCATED CUSTOM MOTD>
$

Update - below is a hackish alternative solution, take it just for bashist exercise, maybe for quick and dirty stuff:

alias ssht='f(){ ssh -p 22 said@192.168.0.$@;unset -f f;}&&f'

What it does

  • Create temporary function
  • Pass all arguments to it
  • Do the SSH connection
  • Once session ends, unset the function so it won't linger around
  • It can take additional arguments, meaning you can chain additional ssh options like tunneling (-L, -R, -D), verbose mode (-vv), no-TTY (-T) etc.

For example I want to start a socks proxy with no terminal

$ ssht 2 -vv -D 1080 -T
OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /home/said/.ssh/config
debug1: /home/said/.ssh/config line 540: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "192.168.0.2" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to 192.168.0.2 [192.168.0.2] port 22.
debug1: Connection established.
<TRUNCATED>
Welcome to Linux Mint 18.1 Serena (GNU/Linux 4.4.0-81-generic x86_64)

 * Documentation:  https://www.linuxmint.com

98 packages can be updated.
0 updates are security updates.

As you can see, no command prompt, it executed with -vv,-T,-D 1080 arguments.

I can verify tunnel (basically SOCKS5 proxy) on my machine, too

$ ss -ltnp | grep 1080
LISTEN     0      128    127.0.0.1:1080                     *:*                   users:(("ssh",pid=17038,fd=6))