ssh
的介绍及使用参看:SSH简介
、建立SSH密钥对
。linux
ssh
程序能够从如下途径获取配置参数:git
配置文件可分为多个配置区段,每一个配置区段使用Host
来区分。咱们能够在命令行中输入不一样的host
来加载不一样的配置段。github
对每个配置项来讲,首次获取的参数值将被采用,所以通用的设置应该放到文件的后面,特定host
相关的配置项应放到文件的前面。vim
下面介绍一些经常使用的SSH
配置项:缓存
Host
配置项标识了一个配置区段。bash
ssh
配置项参数值可使用通配符:*
表明0~n个非空白字符,?
表明一个非空白字符,!
表示例外通配。服务器
咱们能够在系统配置文件中看到一个匹配全部host
的默认配置区段:ssh
$ cat /etc/ssh/ssh_config | grep '^Host' Host *
这里有一些默认配置项,咱们能够在用户配置文件中覆盖这些默认配置。spa
指定一个或多个全局认证主机缓存文件,用来缓存经过认证的远程主机的密钥,多个文件用空格分隔。默认缓存文件为:/etc/ssh/ssh_known_hosts, /etc/ssh/ssh_known_hosts2..net
指定远程主机名,能够直接使用数字IP地址。若是主机名中包含 ‘%h’ ,则实际使用时会被命令行中的主机名替换。
指定密钥认证使用的私钥文件路径。默认为 ~/.ssh/id_dsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ed25519 或 ~/.ssh/id_rsa 中的一个。文件名称可使用如下转义符:
'%d' 本地用户目录 '%u' 本地用户名称 '%l' 本地主机名 '%h' 远程主机名 '%r' 远程用户名
能够指定多个密钥文件,在链接的过程当中会依次尝试这些密钥文件。
指定远程主机端口号,默认为 22 。
指定登陆用户名。
指定一个或多个用户认证主机缓存文件,用来缓存经过认证的远程主机的密钥,多个文件用空格分隔。默认缓存文件为: ~/.ssh/known_hosts, ~/.ssh/known_hosts2.
还有更多参数的介绍,能够参看用户手册:
$ man ssh config
如下链接为例:
SSH 服务器: ssh.test.com 端口号: 2200 帐户: user 密钥文件: ~/.ssh/id_rsa_test
$ ssh -p 2200 -i ~/.ssh/id_rsa_test user@ssh.test.com user@ssh.test.com's password:
$ ssh-copy-id -i ~/.ssh/id_rsa_test user@ssh.test.com /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys user@ssh.test.com's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'user@ssh.test.com'" and check to make sure that only the key(s) you wanted were added. $ ssh user@ssh.test.com
有以下配置文件:
$ vim ~/.ssh/config Host sshtest HostName ssh.test.com User user Port 2200 IdentityFile ~/.ssh/id_rsa_test Host ssttest2 HostName ssh.test2.com User user2 Port 2345 IdentityFile ~/.ssh/id_rsa_test2
使用配置文件登陆:
$ ssh sshtest
$ ssh -f -N -L 9906:127.0.0.1:3306 coolio@database.example.com # -f puts ssh in background # -N makes it not execute a remote command
This will forward all local port 9906
traffic to port 3306
on the remote database.example.com
server, letting me point my desktop GUI to localhost (127.0.0.1:9906
) and have it behave exactly as if I had exposed port 3306
on the remote server and connected directly to it.
Now I don't know about you, but remembering that sequence of flags and options for SSH can be a complete pain. Luckily, our config file can help alleviate that:
Host tunnel HostName database.example.com IdentityFile ~/.ssh/coolio.example.key LocalForward 9906 127.0.0.1:3306 User coolio
Which means I can simply do:
$ ssh -f -N tunnel