Создать псевдоним для подключения ssh

Для Ubuntu 10.10 +

Установка необходимых компонентов - это просто вопрос:

sudo apt-get install xul-ext-lightning xul-ext-gdata-provider

Это установит расширение календаря Lightning и поставщика календаря Google.

Для Ubuntu 10.04

К сожалению, Lightning недоступен в репозиториях Ubuntu для 10.04 пользователей LTS. Если вы используете Ubuntu 10.04 LTS, у вас есть 2 варианта:

32-разрядные пользователи могут установить версию Lightning, совместимую с Thunderbird 3.1, с https://addons.mozilla.org/en-US/thunderbird /addon/lightning/versions/?page=1#version-1.0b2 Вы можете установить последнюю стабильную версию Thunderbird, следуя инструкциям в разделе Как установить последнюю стабильную версию Thunderbird ?. У стабилизирующего thunderbird PPA также есть совместимая версия расширения Lightning для пользователей Ubuntu 10.04 LTS.

Я бы решительно отказался отключить проверку совместимости аддонов, как это было сказано в другом ответе. Проверка существует по очень веской причине, и ее отключение может сделать невозможным использование Thunderbird.

13
задан 2 August 2017 в 16:46

15 ответов

Это вызывает функцию - простую и надежную, тогда как alias в этом случае будет хрупкой.

Что-то вроде этого должно делать:

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
}

условие [[ $1 =~ ^(1|2|3)$ ]] гарантирует, что вы ввели один из 1, 2, 3 в качестве первого аргумента (любой трейлинг-аргумент игнорируется).

Теперь вы можете указать нужный последний октет в качестве первого аргумента:

ssht 1
ssht 2
ssht 3

Поместите это в свой ~/.bashrc, чтобы он был доступен в любом интерактивном сеансе.

21
ответ дан 22 May 2018 в 19:54
  • 1
    Очень хорошо! Однако, чтобы сделать это, замените exit на return и включите пользователя my_user. :) – Karl Morrison 2 August 2017 в 17:30
  • 2
    @KarlMorrison Утверждено. – heemayl 2 August 2017 в 17:38
  • 3
    "Это требует функции " Я использую одно и то же правило большого пальца, если задействованы параметры, используйте функцию вместо псевдонима. – Lasse Meyer 2 August 2017 в 18:34
  • 4
    Мне нравится этот ответ, я думаю, что это будет еще больше с некоторой дополнительной обработкой ввода octet=$1; [[ $octet =~ ^[0-9]+$ ]] && [[ $octet -lt 255 ]] && [[ $octet -gt 0 ]] && ssh -p <portNumber> user@hostname – sdkks 2 August 2017 в 19:42
  • 5
    Хотя это работает, это излишне и не нужно. Просто используйте встроенный файл ~/.ssh/config – ivanivan 3 August 2017 в 05:00

Это вызывает функцию - простую и надежную, тогда как alias в этом случае будет хрупкой.

Что-то вроде этого должно делать:

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 }

условие [[ $1 =~ ^(1|2|3)$ ]] гарантирует, что вы ввели один из 1, 2, 3 в качестве первого аргумента (любой трейлинг-аргумент игнорируется).

Теперь вы можете указать нужный последний октет в качестве первого аргумента:

ssht 1 ssht 2 ssht 3

Поместите это в свой ~/.bashrc, чтобы он был доступен в любом интерактивном сеансе.

21
ответ дан 18 July 2018 в 09:12

Это вызывает функцию - простую и надежную, тогда как alias в этом случае будет хрупкой.

Что-то вроде этого должно делать:

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 }

условие [[ $1 =~ ^(1|2|3)$ ]] гарантирует, что вы ввели один из 1, 2, 3 в качестве первого аргумента (любой трейлинг-аргумент игнорируется).

Теперь вы можете указать нужный последний октет в качестве первого аргумента:

ssht 1 ssht 2 ssht 3

Поместите это в свой ~/.bashrc, чтобы он был доступен в любом интерактивном сеансе.

21
ответ дан 24 July 2018 в 19:16

Используйте назначенный путь и напишите параметры и псевдонимы в ~/.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

и т. д. ...

И затем подключитесь только с помощью

[F2]
50
ответ дан 22 May 2018 в 19:54
  • 1
    Я думаю, что OP пытается автоматически подключиться к чему-то, что принимает один аргумент (последний октет), а не статически помещать что-либо (тогда это был бы лучший подход). – heemayl 2 August 2017 в 17:18
  • 2
    Трудно догадаться, если это запрос для динамических или статических псевдонимов. Но это стандартный способ упростить запись, и даже если это будет динамично, он может избавиться от написания порта и пользователя. Другие ответы уже обсуждают возможности домашнего использования, как это сделать с помощью функций bash. – Jakuje 2 August 2017 в 17:21
  • 3
    @Jakuje heemayl правильный. Мне нужно уметь аргументировать. В противном случае этот метод был выбран как ответ :) – Karl Morrison 2 August 2017 в 17:43
  • 4
    Вы все же можете предоставить строку конфигурации ssh для Host 123.123.123.*, которая указывает порт и имя пользователя! – Riking 2 August 2017 в 20:32
  • 5
    @Riking Спасибо за комментарий. Да. Кроме того, IP будет автозаполнен, поэтому в основном вы будете писать только последний номер. – Jakuje 2 August 2017 в 21:50

Вы можете использовать шаблоны в ~/.ssh/config. Из 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.?

В сочетании с:

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.

Итак, в вашем ~/.ssh/config, поставьте:

Host ?
    Hostname 123.123.123.%h
    Port 12345
    User my_user

Затем:

$ 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
16
ответ дан 22 May 2018 в 19:54
  • 1
    Лучший ответ - твой, а не тот, который мне очень нужен;) – Ravexina 3 August 2017 в 08:31

Используйте функцию вместо:

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

Лучшим решением является использование файла ssh config:

touch ~/.ssh/config

с некоторыми строками, похожими на:

Host some-name
    HostName 123.123.123.1
    User your_user
    Port 22

Вы также можете использовать клавиши ssh для повышения скорости, в конце концов вы запускаете:

ssh some-name

и вы подключены к этому серверу.

6
ответ дан 22 May 2018 в 19:54
  • 1
    Как использовать псевдоним с функцией? Должен ли я помещать это в .bashrc? – Karl Morrison 2 August 2017 в 16:53
  • 2
    Да, вы должны поместить его где-то, как .bashrc или .bash_func, затем введите его в свой файл .bashrc. – Ravexina 2 August 2017 в 16:55

Вам даже не нужно использовать такое имя, как ssht. Имена, начинающиеся с цифр, и даже цифры являются допустимыми именами хостов в конфигурационном файле ssh.

Ниже работает над Xubuntu Xenial

Часть моей ~ / .ssh / config

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

Команда, которую я запускаю (ниже я добавил -vv для подробного ведения журнала до STDOUT по вашему экрану по умолчанию)

ssh -vv 1

Выход

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>
$

Обновление - ниже - это хакерское альтернативное решение, возьмите его только для упражнений с бахистом, возможно, для быстрого и грязного материала:

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

Что он делает

Создает временную function Передайте все аргументы к нему. Соедините SSH. После завершения сеанса отключите функцию, чтобы она не задерживалась. Это может привести к дополнительным аргументам, что означает, что вы можете связать дополнительные параметры ssh, такие как туннелирование (-L, -R, -D), verbose mode (-vv), no-TTY (-T) и т. д.

Например, я хочу запустить прокси-сервер socks без терминала

$ 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.

Как вы можете видеть, нет командной строки, она выполнена с параметрами -vv, -T, -D 1080.

Я могу проверить туннель (в основном прокси SOCKS5) на моей машине тоже

$ ss -ltnp | grep 1080
LISTEN     0      128    127.0.0.1:1080                     *:*                   users:(("ssh",pid=17038,fd=6))
2
ответ дан 22 May 2018 в 19:54

Используйте назначенный путь и напишите параметры и псевдонимы в ~/.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

и т. д. ...

И затем подключитесь только с помощью

[F2]
50
ответ дан 18 July 2018 в 09:12

Вы можете использовать шаблоны в ~/.ssh/config. Из 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.?

В сочетании с:

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.

Итак, в вашем ~/.ssh/config, поставьте:

Host ? Hostname 123.123.123.%h Port 12345 User my_user

Затем:

$ 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
16
ответ дан 18 July 2018 в 09:12

Используйте функцию вместо:

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

Лучшим решением является использование файла ssh config:

touch ~/.ssh/config

с некоторыми строками, похожими на:

Host some-name HostName 123.123.123.1 User your_user Port 22

Вы также можете использовать клавиши ssh для повышения скорости, в конце концов вы запускаете:

ssh some-name

и вы подключены к этому серверу.

6
ответ дан 18 July 2018 в 09:12

Вам даже не нужно использовать такое имя, как ssht. Имена, начинающиеся с цифр, и даже цифры являются допустимыми именами хостов в конфигурационном файле ssh.

Ниже работает над Xubuntu Xenial

Часть моей ~ / .ssh / config

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

Команда, которую я запускаю (ниже я добавил -vv для подробного ведения журнала до STDOUT по вашему экрану по умолчанию)

ssh -vv 1

Выход

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> $

Обновление - ниже - это хакерское альтернативное решение, возьмите его только для упражнений с бахистом, возможно, для быстрого и грязного материала:

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

Что он делает

Создает временную function Передайте все аргументы к нему. Соедините SSH. После завершения сеанса отключите функцию, чтобы она не задерживалась. Она может принимать дополнительные аргументы, что означает, что вы можете связать дополнительные параметры ssh, такие как туннелирование (-L, -R, -D), verbose mode (-vv), no-TTY (-T) и т. д.

Например, я хочу запустить прокси-сервер socks без терминала

$ 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.

Как вы можете видеть, нет командной строки, она выполнена с параметрами -vv, -T, -D 1080.

Я могу проверить туннель (в основном прокси SOCKS5) на моей машине тоже

$ ss -ltnp | grep 1080 LISTEN 0 128 127.0.0.1:1080 *:* users:(("ssh",pid=17038,fd=6))
2
ответ дан 18 July 2018 в 09:12

Используйте назначенный путь и напишите параметры и псевдонимы в ~/.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

и т. д. ...

И затем подключитесь только с помощью

[F2]
50
ответ дан 24 July 2018 в 19:16
  • 1
    Я думаю, что OP пытается автоматически подключиться к чему-то, что принимает один аргумент (последний октет), а не статически помещать что-либо (тогда это был бы лучший подход). – heemayl 2 August 2017 в 17:18
  • 2
    Трудно догадаться, если это запрос для динамических или статических псевдонимов. Но это стандартный способ упростить запись, и даже если это будет динамично, он может избавиться от написания порта и пользователя. Другие ответы уже обсуждают возможности домашнего использования, как это сделать с помощью функций bash. – Jakuje 2 August 2017 в 17:21
  • 3
    @Jakuje heemayl правильный. Мне нужно уметь аргументировать. В противном случае этот метод был выбран как ответ :) – Karl Morrison 2 August 2017 в 17:43
  • 4
    Вы все же можете предоставить строку конфигурации ssh для Host 123.123.123.*, которая указывает порт и имя пользователя! – Riking 2 August 2017 в 20:32
  • 5
    @Riking Спасибо за комментарий. Да. Кроме того, IP будет автозаполнен, поэтому в основном вы будете писать только последний номер. – Jakuje 2 August 2017 в 21:50

Вы можете использовать шаблоны в ~/.ssh/config. Из 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.?

В сочетании с:

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.

Итак, в вашем ~/.ssh/config, поставьте:

Host ? Hostname 123.123.123.%h Port 12345 User my_user

Затем:

$ 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
16
ответ дан 24 July 2018 в 19:16
  • 1
    Лучший ответ - твой, а не тот, который мне очень нужен;) – Ravexina 3 August 2017 в 08:31

Используйте функцию вместо:

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

Лучшим решением является использование файла ssh config:

touch ~/.ssh/config

с некоторыми строками, похожими на:

Host some-name HostName 123.123.123.1 User your_user Port 22

Вы также можете использовать клавиши ssh для повышения скорости, в конце концов вы запускаете:

ssh some-name

и вы подключены к этому серверу.

6
ответ дан 24 July 2018 в 19:16
  • 1
    Как использовать псевдоним с функцией? Должен ли я помещать это в .bashrc? – Karl Morrison 2 August 2017 в 16:53
  • 2
    Да, вы должны поместить его где-то, как .bashrc или .bash_func, затем введите его в свой файл .bashrc. – Ravexina 2 August 2017 в 16:55

Вам даже не нужно использовать такое имя, как ssht. Имена, начинающиеся с цифр, и даже цифры являются допустимыми именами хостов в конфигурационном файле ssh.

Ниже работает над Xubuntu Xenial

Часть моей ~ / .ssh / config

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

Команда, которую я запускаю (ниже я добавил -vv для подробного ведения журнала до STDOUT по вашему экрану по умолчанию)

ssh -vv 1

Выход

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> $

Обновление - ниже - это хакерское альтернативное решение, возьмите его только для упражнений с бахистом, возможно, для быстрого и грязного материала:

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

Что он делает

Создает временную function Передайте все аргументы к нему. Соедините SSH. После завершения сеанса отключите функцию, чтобы она не задерживалась. Она может принимать дополнительные аргументы, что означает, что вы можете связать дополнительные параметры ssh, такие как туннелирование (-L, -R, -D), verbose mode (-vv), no-TTY (-T) и т. д.

Например, я хочу запустить прокси-сервер socks без терминала

$ 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.

Как вы можете видеть, нет командной строки, она выполнена с параметрами -vv, -T, -D 1080.

Я могу проверить туннель (в основном прокси SOCKS5) на моей машине тоже

$ ss -ltnp | grep 1080 LISTEN 0 128 127.0.0.1:1080 *:* users:(("ssh",pid=17038,fd=6))
2
ответ дан 24 July 2018 в 19:16

Другие вопросы по тегам:

Похожие вопросы: