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