OpenSSH

出自 Arch Linux 中文维基

這篇文章或章節的翻譯不反映原文。

原因:Partial translation, missing a huge chunk of the English page.(在 Talk:OpenSSH# 中討論)

OpenSSH(OpenBSD Secure Shell)是使用Secure Shell(SSH)協議,在計算機網絡上提供加密通信會話的程序包。它是 SSH Communications Security 提供的專有 Secure Shell 軟件的開源替代方案。OpenSSH 是 OpenBSD 項目的一部分,該項目由 Theo de Raadt 領導。

OpenSSH 有時候會與名字相似的 OpenSSL 相混淆;然而,它們的目的不同,開發團隊也不同,名字相似只因為兩者目標相似。

安裝[編輯 | 編輯原始碼]

安裝 openssh

客戶端用法[編輯 | 編輯原始碼]

連接伺服器:

$ ssh -p 端口 用户名@服务器地址

如果伺服器只允許公鑰認證,參考 SSH 密鑰

配置[編輯 | 編輯原始碼]

客戶端可以配置一些通用的參數和主機信息。所有的參數都可以被聲明為全局的或者限制為特定主機,例如:

~/.ssh/config
# 全局選項
User 用戶名

# 特定於主機的選項
Host myserver
    Hostname 伺服器地址
    Port     端口

這樣配置之後,下面的命令是等價的:

$ ssh -p 端口 用户名@服务器地址
$ ssh myserver

參考 ssh_config(5) 可以獲得更多的信息。

一些參數沒有對應的命令行選項,但你可以在命令行中使用 -o 指定配置選項。例如 -oKexAlgorithms=+diffie-hellman-group1-sha1

服務端用法[編輯 | 編輯原始碼]

sshd 是 OpenSSH 伺服器守護程序,通過 /etc/ssh/sshd_config 配置並由 sshd.service 管理。每次更改配置後,請在重新啟動服務前在測試模式下運行 sshd 以確保它能夠乾淨地啟動。有效配置將不會產生輸出。

# sshd -t

配置[編輯 | 編輯原始碼]

要僅允許某些用戶訪問,請添加以下一行:

AllowUsers    用户1 用户2

要僅允許某些用戶組訪問:

AllowGroups   用户组1 用户组2

要添加漂亮的歡迎消息(例如,輸出 /etc/issue 文件),請配置 Banner 選項:

Banner /etc/issue

sshdgenkeys 服務會自動在 /etc/ssh 中生成缺失的任何算法的公鑰和私鑰,即使 sshd_config 中的 HostKeyAlgorithms 選項只允許部分加密算法。OpenSSH 提供了三種基於 rsa、ecdsa 和 ed25519 算法的密鑰對。要讓 sshd 使用特定的密鑰,請指定以下選項:

HostKey /etc/ssh/ssh_host_rsa_key

如果伺服器要暴露在 WAN 中,建議將默認端口從 22 更改為更高的隨機端口,例如:

Port 39901
提示:
  • 要選擇尚未分配給常見服務的備用端口,請查看 TCP 和 UDP 端口號列表。還可以在本地的 /etc/services 中查找端口信息。更改 OpenSSH 所使用的端口有助於減少由攻擊者使用自動程序嘗試通過 SSH 登錄你的伺服器的情況(但無法徹底解決)。查看 Port knocking 了解相關內容。
  • 建議完全禁用密碼登錄。這將大大提高安全性,更多信息請參見#強制公鑰認證。更多推薦的安全方法,請參閱#保護
  • OpenSSH 可以監聽多個端口,只需在配置文件中添加多個 Port 端口號
  • 可以通過從 /etc/ssh 中刪除要替換的主機密鑰對並以 root 身份運行 ssh-keygen -A 來生成新的(或缺失的)主機密鑰對。

管理守護程序[編輯 | 編輯原始碼]

啟動/啟用 sshd.service。它將保持 SSH 守護程序始終處於活動狀態,並為每個傳入連接 fork。[1]

注意:sshd.socket 易受到拒絕服務攻擊的影響,openssh 8.0p1-3 刪除了它. 點擊 FS#62248 查看詳情。如果在更新到 openssh 8.0p1-3 時啟用了 sshd.socket,則 sshd.socketsshd@.service 單元將被複製到 /etc/systemd/system/ 並重新啟用。這樣做只是為了不破壞現有設置;仍然建議用戶遷移到 sshd.service
警告: 如果你繼續使用 sshd.socket, 請注意下列問題:
  • sshd.socket units 可能會失敗 (例如:在內存耗盡的情況下) 並且 Restart=always 不能用於 socket units. 點擊 systemd issue 11553 了解更多內容.
  • 使用套接字激活會導致拒絕服務,因為太多的連接會導致拒絕進一步激活服務。見 FS#62248.
注意: sshd.socket 使得 ListenAddress 設置失效,因此它會允許連接任意地址。為了使 ListenAddress 設置起作用,你必須編輯 sshd.socket 來為ListenStream 指定端口"和"IP (例如 ListenStream=192.168.1.100:22) 。你還必須在 [Socket] 添加 FreeBind=true ,否則設置IP位址會有 ListenAddress設置一樣的缺點:如果網絡沒有及時啟動,套接字會啟動失敗。
提示:當使用套接字激活時,每個連接(不同的實例名稱)都會啟動一個sshd@.service的瞬態實例,同時,不論是sshd.socket還是常規守護進程sshd.service都會允許在日誌中監控連接嘗試。通過root運行journalctl -u "sshd@*"或者journalctl /usr/bin/sshd可以查看SSH套接字激活實例的日誌。

保護[編輯 | 編輯原始碼]

允許通過 SSH 遠程登錄有利於管理,但可能會威脅伺服器的安全。由於 SSH 訪問通常是暴力攻擊的目標,因此需要適當限制 SSH 訪問以防止第三方訪問伺服器。

ssh-audit 提供對服務端和客戶端配置的自動分析。關於這個主題,還有其他幾個很好的指南和工具,例如:

強制公鑰認證[編輯 | 編輯原始碼]

如果客戶端無法通過公鑰進行身份驗證,SSH 服務端默認會退回到使用密碼進行身份驗證,從而允許惡意用戶嘗試通過暴力窮舉密碼來獲取訪問權限。防止這種攻擊的最有效方法之一是完全禁用密碼登錄,並強制使用 SSH 密鑰。這可以通過在守護程序配置文件中設置以下選項來完成:

/etc/ssh/sshd_config
PasswordAuthentication no
AuthenticationMethods publickey
警告: 在將此添加到配置之前,請確保所有需要 SSH 訪問的帳戶都在相應的 authorized_keys 文件中設置了公鑰身份驗證。詳細信息請參閱 SSH 密鑰#將公鑰複製到遠程伺服器上

雙重身份認證[編輯 | 編輯原始碼]

SSH 可以被設置成需要多重驗證。你可以通過 AuthenticationMethods 選項指定使用哪些驗證方式。它將啟用使用公鑰作為兩步驗證。

身份驗證提供程序[編輯 | 編輯原始碼]

查看 Google Authenticator 去設置 Google 身份驗證器. 對於 Duo安裝 提供 pam_duo.so 模塊的包 duo_unixAUR 。閱讀Duo Unix說明文件以了解如何設置Duo憑據(Integration Key, Secret Key, API Hostname)。

PAM 設置[編輯 | 編輯原始碼]

要在 OpenSSH 中使用 PAM 請編輯下列文件:

/etc/ssh/sshd_config
KbdInteractiveAuthentication yes
AuthenticationMethods publickey keyboard-interactive:pam

然後你可以通過公鑰 在 PAM 中設置的用戶身份驗證方法登錄: 另一方面,如果您想要根據 PAM 設置的要求在公鑰 用戶身份驗證上對用戶進行身份驗證,請使用逗號而不是空格來分隔 AuthenticationMethods:

/etc/ssh/sshd_config
KbdInteractiveAuthentication yes
AuthenticationMethods publickey,keyboard-interactive:pam

為了必需使用 pubkey 和 pam 身份驗證,您可能希望禁用密碼登錄:

/etc/pam.d/sshd
auth      required  pam_securetty.so     #disable remote root
#Require google authenticator
auth      required  pam_google_authenticator.so
#But not password
#auth      include   system-remote-login
account   include   system-remote-login
password  include   system-remote-login
session   include   system-remote-login

防止暴力窮舉攻擊[編輯 | 編輯原始碼]

限制root用戶登錄[編輯 | 編輯原始碼]

拒絕[編輯 | 編輯原始碼]
限制[編輯 | 編輯原始碼]

對 authorized_keys 文件加鎖[編輯 | 編輯原始碼]

Tips and tricks[編輯 | 編輯原始碼]

使用加密的SOCKS隧道[編輯 | 編輯原始碼]

本文或本章節的語言、語法或風格需要改進。參考:Help:Style

原因:Written like a blog post.(在Talk:OpenSSH討論)

這對連接到各種不安全無線連接的筆記本電腦用戶非常有用。你唯一需要的是在一個有點安全的地方運行的SSH伺服器,比如你的家或工作地點。使用動態DNS服務可能很有用,如DynDNS,這樣你就不必記住你的IP位址。

步驟 1:開始連接[編輯 | 編輯原始碼]

你只需要執行這一條命令就可以開始連接:

$ ssh -TND 4711 user@host

其中 user 是你在 host 上運行的 SSH 伺服器的用戶名。它將詢問你的密碼,然後連接將被建立。N標誌禁用了交互式提示,D標誌指定了監聽的本地端口(如果你願意,可以選擇任何端口號)。 T標誌禁用偽終端分配。

添加 verbose(-v)標誌是很好的,因為這樣你就可以從該輸出中驗證它是否真的連接。

步驟 2 (方法 A):配置你的瀏覽器(或者其它程序)[編輯 | 編輯原始碼]

上述步驟僅在與使用新創建的socks隧道的web瀏覽器或其他程序結合使用時有用。因為SSH現在同時支持SOCKS v4和SOCKS v5,你可以選擇他們中的任意一種。

  • 對於Firefox:在首選項 > 通用 找到頁面底部並點擊設置...,它在網絡設置右邊。接下來,在新的小窗口,選中 手動代理配置 並在SOCKS主機名框內輸入localhost,在旁邊的 端口框 輸入端口(上述例子4711)。
Firefox不會自動通過socks隧道發出DNS請求,這種潛在的問題可以通過往下翻,使用SOCKS v5輸入代理DNS來解決。很明顯,這隻有在選擇SOCKS v5而不是v4時才有效。
  • 對於Chromium:可以設置SOCKS作為環境變量或者通過命令行,我建議在.bashrc添加以下函數:
function secure_chromium {
    port=4711
    export SOCKS_SERVER=localhost:$port
    export SOCKS_VERSION=5
    chromium &
    exit
}

或者

function secure_chromium {
    port=4711
    chromium --proxy-server="socks://localhost:$port" &
    exit
}

現在打開命令行僅需這樣做:

$ secure_chromium

Enjoy your secure tunnel!

步驟 2 (方法 B):配置本地TUN接口[編輯 | 編輯原始碼]

這種方法在前期稍微複雜,但後期是你不必逐個手動配置每個應用程式來使用SOCKS代理。它涉及到建立一個本地TUN接口並通過該接口路由流量。

查看 VPN over SSH#Set up badvpn and tunnel interface.

X11 轉發[編輯 | 編輯原始碼]

X11 轉發是一種機制,它允許運行在遠程系統的X11程序的圖形界面顯示在本地客戶端上。對於X11轉發,遠程主機不需要有完整安裝的X11系統;但是,至少需要安裝xauthxauth是維護Xauthority配置的實用工具,這個配置用於X11會話服務端和客戶端的認證(source)。

警告: X11 轉發有很強的安全性,至少要通過閱讀ssh(1), sshd_config(5), 和 ssh_config(5) 手冊可以承認這一點。也可看 this StackExchange question.

設置[編輯 | 編輯原始碼]

服務端[編輯 | 編輯原始碼]
  • 安裝 xorg-xauth
  • /etc/ssh/sshd_config:
    • 設置 X11Forwardingyes
    • 檢查 AllowTcpForwardingX11UseLocalhost 選項為 yes, 並且 X11DisplayOffset 設為 10 (這是默認值除非被修改過,參考 sshd_config(5))
  • 然後重啟這個 sshd daemon.
客戶端[編輯 | 編輯原始碼]
提示:如果GUI繪製不好或者顯示錯誤,你可以啟動 ForwardX11Trusted 選項 (-Y 切換為命令行),這會防止X11轉發受到 X11 SECURITY extension 的影響。如果你需要這樣做,在開始這部分之前確保你已經閱讀 the warning

Usage[編輯 | 編輯原始碼]

正常登錄到遠程機器,如果客戶端的配置文件中沒有啟用 ForwardX11,則指定 -X 開關:

$ ssh -X user@host

如果你在試圖運行圖形應用程式時收到錯誤,請嘗試用 ForwardX11Trusted 代替:

$ ssh -Y user@host

如果獲得輸出 X11 forwarding request failed,則需要為你的遠程機器重新進行設置。一旦X11轉發請求成功,你可以在遠程伺服器上啟動任何 X 程序,它將被轉發到你的本地會話。

$ xclock

包含 Can't open display 的錯誤輸出表示 DISPLAY 設置不正確。 對一些應用程式要小心,因為它們會檢查本地機器上是否有正在運行的實例。 Firefox 是一個例子:要麼關閉正在運行的 Firefox 實例,要麼使用下面的啟動參數在本地機器上啟動一個遠程實例。

$ firefox --no-remote

如果你在連接時得到 "X11 forwarding request failed on channel 0"(並且伺服器 /var/log/errors.log 顯示 "Failed to allocate internet-domain X11 display socket"),確保軟件包 xorg-xauth 已經安裝。If its installation is not working, try to either:

  • sshd_configserver 中啟用 AddressFamily any 選項,或者
  • sshd_config 中的 server 中設置 AddressFamily 選項設置為 inet。

將其設置為 inet 可能會解決 Ubuntu 客戶端在 IPv4 上的問題。

對於在 SSH 伺服器上以另一個用戶身份運行 X 應用程式,you need to xauth add the authentication line taken from xauth list of the SSH logged in user.

轉發其他端口[編輯 | 編輯原始碼]

除了SSH對X11的內置支持外,它還可以通過使用本地轉發或遠程轉發來安全地隧道傳輸任何TCP連接。 本地轉發打開本地計算機上的一個端口,連接將被轉發到遠程主機,並從那裏轉發到給定的目的地。通常,轉發目的地將與遠程主機相同,從而為同一機器提供安全外殼,例如安全VNC連接。本地轉發是通過-L交換機實現的,它是以-L交換機形式附帶的轉發規範,也是以<隧道端口>:<目的地地址>:<目標端口>形式附帶的發送規範。

因此:

$ ssh -L 1000:mail.google.com:25 192.168.0.100

將使用SSH登錄並打開上的shell192.168.0.100, 並且還將創建從本地機器的TCP端口1000到端口25上的mail.google.com的隧道。一旦建立,連接到.google.com的25端口. 一旦建立, 連接到localhost:1000 將連接到Gmail SMTP端口。對於谷歌,任何這樣的連接都會出現 (儘管不一定是通過連接傳輸的數據) 來源於192.168.0.100, 並且這樣的數據在本地機器和192.168.0.100之間是安全的,但在192.168.0.100 和谷歌之間不是安全的,除非採取其他措施。

類似地:

$ ssh -L 2000:192.168.0.100:6001 192.168.0.100

will allow connections to localhost:2000 which will be transparently sent to the remote host on port 6001. The preceding example is useful for VNC connections using the vncserver utility--part of the tightvnc package--which, though very useful, is explicit about its lack of security.

Remote forwarding allows the remote host to connect to an arbitrary host via the SSH tunnel and the local machine, providing a functional reversal of local forwarding, and is useful for situations where, e.g., the remote host has limited connectivity due to firewalling. It is enabled with the -R switch and a forwarding specification in the form of <tunnel port>:<destination address>:<destination port>.

Thus:

$ ssh -R 3000:irc.libera.chat:6667 192.168.0.200

will bring up a shell on 192.168.0.200, and connections from 192.168.0.200 to itself on port 3000 (the remote host's localhost:3000) will be sent over the tunnel to the local machine and then on to irc.libera.chat on port 6667, thus, in this example, allowing the use of IRC programs on the remote host to be used, even if port 6667 would normally be blocked to it.

Both local and remote forwarding can be used to provide a secure "gateway", allowing other computers to take advantage of an SSH tunnel, without actually running SSH or the SSH daemon by providing a bind-address for the start of the tunnel as part of the forwarding specification, e.g. <tunnel address>:<tunnel port>:<destination address>:<destination port>. The <tunnel address> can be any address on the machine at the start of the tunnel. The address localhost allows connections via the localhost or loopback interface, and an empty address or * allow connections via any interface. By default, forwarding is limited to connections from the machine at the "beginning" of the tunnel, i.e. the <tunnel address> is set to localhost. Local forwarding requires no additional configuration; however, remote forwarding is limited by the remote server's SSH daemon configuration. See the GatewayPorts option in sshd_config(5) and -L address option in ssh(1) for more information about remote forwarding and local forwarding, respectively.

Jump hosts[編輯 | 編輯原始碼]

有時,可能無法直接連接到目標的SSH守護程序,因而需要使用一個跳轉伺服器(或堡壘伺服器)。為此,我們試圖將兩個或更多的 SSH 隧道連接在一起,並假設你的本地密鑰對鏈上的每個伺服器都有授權。這可以通過 SSH 代理轉發(-A)和偽終端分配(-t)來實現,偽終端分配以下列語法轉發你的本地密鑰。

$ ssh -A -t -l user1 bastion1 \
  ssh -A -t -l user2 intermediate2 \
  ssh -A -t -l user3 target

一個更簡單的方法是使用-J

$ ssh -J user1@bastion1,user2@intermediate2 user3@target

-J 指令中的多個主機可以用逗號隔開;它們將按照列出的順序被連接到。user...@ 部分不是必須的,但可以使用。The host specifications for -J use the ssh configuration file, so specific per-host options can be set there, if needed.

-J標誌相當於配置文件中ProxyJump選項。詳情見ssh_config(5)

Reverse SSH through a relay[編輯 | 編輯原始碼]

本文或本章節的語言、語法或風格需要改進。參考:Help:Style

原因:The idea of SSH tunneling is classic, so some references for detailed explanation would be nice. E.g. [2] which includes other scenarios.(在Talk:OpenSSH討論)

The idea is that the client connects to the server via another relay while the server is connected to the same relay using a reverse SSH tunnel. This is useful when the server is behind a NAT, and the relay is a publicly accessible SSH server used as a proxy to which the user has access. Therefore, the prerequisite is that the client's keys are authorized against both the relay and the server, and the server needs to be authorized against the relay as well for the reverse SSH connection.

The following configuration example assumes that user1 is the user account used on client, user2 on relay and user3 on server. First, the server needs to establish the reverse tunnel with:

ssh -R 2222:localhost:22 -N user2@relay

Which can also be automated with a startup script, systemd service or autossh.

這篇文章的某些內容需要擴充。

原因: Explain why ssh user3@relay -p 2222 is not sufficient. (在 Talk:OpenSSH 中討論)

At the client side, the connection is established with:

ssh -t user2@relay ssh user3@localhost -p 2222

The remote command to establish the connection to reverse tunnel can also be defined in relay's ~/.ssh/authorized_keys by including the command field as follows:

command="ssh user3@localhost -p 2222" ssh-rsa KEY2 user1@client

In this case the connection is established with:

ssh user2@relay

Note that SCP's autocomplete function in client's terminal is not working and even the SCP transfers themselves are not working under some configurations.

Multiplexing[編輯 | 編輯原始碼]

SSH守護進程通常監聽 22 端口。然而,許多公共互聯網熱點地區通常會屏蔽所有不在常規HTTP/S端口(分別為80和443)的流量,從而阻止了SSH連接。最直接解決這個問題的辦法是讓 sshd 額外監聽白名單中的一個端口。

/etc/ssh/sshd_config
Port 22
Port 443

然而,443 端口很可能已經被提供 HTTPS 伺服器使用,在這種情況下,可以使用一個多路復用器,如 sslh,它監聽多路復用端口,可以智能地將數據包轉發給許多服務。

Speeding up SSH[編輯 | 編輯原始碼]

There are several client configuration options which can speed up connections either globally or for specific hosts. See ssh_config(5) for full descriptions of these options.

  • Use a faster cipher: on modern CPUs with AESNI instructions, aes128-gcm@openssh.com and aes256-gcm@openssh.com should offer significantly better performance over openssh's default preferred cipher, usually chacha20-poly1305@openssh.com. Cipher can be selected with the -c flag. For a permanent effect, put Ciphers option in your ~/.ssh/config with ciphers in new preferred order, e.g.:
    Ciphers aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
  • Enable or disable compression: compression can increase speed on slow connections; it is enabled with the Compression yes option or the -C flag. However, the compression algorithm used is the relatively slow gzip(1) which becomes the bottleneck on fast networks. In order to speed up the connection, one should use the Compression no option on local or fast networks.
  • Connection sharing: you can make all sessions to the same host share a single connection using these options:
    ControlMaster auto
    ControlPersist yes
    ControlPath ~/.ssh/sockets/socket-%r@%h:%p
    
where ~/.ssh/sockets can be any directory not writable by other users.

ControlPersist specifies how long the master should wait in the background for new clients after the initial client connection has been closed. Possible values are either:

    • no to close the connection immediately after the last client disconnects,
    • a time in seconds,
    • yes to wait forever, the connection will never be closed automatically.
  • Login time can be shortened by bypassing IPv6 lookup using the AddressFamily inet option or -4 flag.
  • Last, if you intend to use SSH for SFTP or SCP, High Performance SSH/SCP can significantly increase throughput by dynamically raising the SSH buffer sizes. Install the package openssh-hpn-gitAUR to use a patched version of OpenSSH with this enhancement.

使用 SSHFS 掛載一個遠程的文件系統[編輯 | 編輯原始碼]

請查看 SSHFS 文章,將 SSH 可訪問的遠程系統安裝到本地目錄。這樣您就可以使用任何工具對安裝的文件執行任何操作(複製、重命名、使用 vim 編輯等)。sshfs 一般優於 shfs,後者自 2004 年以來一直沒有更新。

保活[編輯 | 編輯原始碼]

默認情況下,如果 SSH 會話已經空閒了一段時間,它將自動註銷。 為了保持會話,如果在一段時間內沒有收到數據,客戶端可以向伺服器發送保持活動的信號,或者如果伺服器沒有收到客戶端的消息,則可以對稱地定期發送消息。

  • 在 'server 端,ClientAliveInterval 以秒為單位設置超時,如果沒有從客戶端接收到數據,sshd 將發送響應請求。默認值為 0,不發送消息。例如,要每 60 秒從客戶端請求一次響應,請在 server configuration 中設置 ClientAliveInterval 60 選項。另見 ClientAliveCountMaxTCPKeepAlive 選項。
  • 在 'client 端,ServerAliveInterval 控制從客戶端發送到伺服器的響應請求之間的間隔。例如,要請求伺服器每 120 秒響應一次,請將 ServerAliveInterval 120 選項添加到 client configuration。另請參見 ServerAliveCountMaxTCPKeepAlive 選項。


注意: 為了確保會話保持活動狀態,客戶機或伺服器中只有一個需要發送 keep alive 請求。 如果同時控制伺服器和客戶機,一個合理的選擇是只配置需要持久會話的客戶機,並使其他客戶機和伺服器保持默認配置。

Automatically restart SSH tunnels with systemd[編輯 | 編輯原始碼]

systemd can automatically start SSH connections on boot/login and restart them when they fail. This makes it a useful tool for maintaining SSH tunnels.

The following service can start an SSH tunnel on login using the connection settings in your ssh configuration. If the connection closes for any reason, it waits 10 seconds before restarting it:

~/.config/systemd/user/tunnel.service
[Unit]
Description=SSH tunnel to myserver

[Service]
Type=simple
Restart=always
RestartSec=10
ExecStart=/usr/bin/ssh -F %h/.ssh/config -N myserver

Then enable and start the Systemd/User service. See #Keep alive for how to prevent the tunnel from timing out. If you wish to start the tunnel on boot, you might want to rewrite the unit as a system service.

Autossh - automatically restarts SSH sessions and tunnels[編輯 | 編輯原始碼]

When a session or tunnel cannot be kept alive, for example due to bad network conditions causing client disconnections, you can use autossh to automatically restart them.

Usage examples:

$ autossh -M 0 -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2" username@example.com

Combined with SSHFS:

$ sshfs -o reconnect,compression=yes,transform_symlinks,ServerAliveInterval=45,ServerAliveCountMax=2,ssh_command='autossh -M 0' username@example.com: /mnt/example 

Connecting through a SOCKS-proxy set by Proxy settings:

$ autossh -M 0 -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2" -NCD 8080 username@example.com 

With the -f option autossh can be made to run as a background process. Running it this way however means the passphrase cannot be entered interactively.

The session will end once you type exit in the session, or the autossh process receives a SIGTERM, SIGINT of SIGKILL signal.

Run autossh automatically at boot via systemd[編輯 | 編輯原始碼]

If you want to automatically start autossh, you can create a systemd unit file:

/etc/systemd/system/autossh.service
[Unit]
Description=AutoSSH service for port 2222
After=network.target

[Service]
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/bin/autossh -M 0 -NL 2222:localhost:2222 -o TCPKeepAlive=yes foo@bar.com

[Install]
WantedBy=multi-user.target

Here AUTOSSH_GATETIME=0 is an environment variable specifying how long ssh must be up before autossh considers it a successful connection, setting it to 0 autossh also ignores the first run failure of ssh. This may be useful when running autossh at boot. Other environment variables are available at autossh(1). Of course, you can make this unit more complex if necessary (see the systemd documentation for details), and obviously you can use your own options for autossh, but note that the -f implying AUTOSSH_GATETIME=0 does not work with systemd.

Remember to start and/or enable the service afterwards.

You may also need to disable ControlMaster e.g.

ExecStart=/usr/bin/autossh -M 0 -o ControlMaster=no -NL 2222:localhost:2222 -o TCPKeepAlive=yes foo@bar.com
提示:It is also easy to maintain several autossh processes, to keep several tunnels alive. Just create multiple service files with different names.

Alternative service should SSH daemon fail[編輯 | 編輯原始碼]

For remote or headless servers which rely exclusively on SSH, a failure to start the SSH daemon (e.g., after a system upgrade) may prevent administration access. systemd offers a simple solution via OnFailure option.

Let us suppose the server runs sshd and telnet is the fail-safe alternative of choice. Create a file as follows. Do not enable telnet.socket!

/etc/systemd/system/sshd.service.d/override.conf
[Unit]
OnFailure=telnet.socket

That's it. Telnet is not available when sshd is running. Should sshd fail to start, a telnet session can be opened for recovery.

Terminal background color based on host[編輯 | 編輯原始碼]

為了更好地區分在不同主機上的情況,可以設置 基於主機類型的不同背景顏色 。 這種解決方案僅限於 ZSH。

Network specific configuration[編輯 | 編輯原始碼]

You can use host configuration specific to the network you are connected to using a Match exec.

For example, when using nmcli, and the connection is configured (manually or through DHCP) to use a search-domain:

Match exec "nmcli | grep domains: | grep example.com"
  CanonicalDomains example.com
  # Should you use a different username on this network
  #User username
  # Use a different known_hosts file (for private network or synchronisation)
  #UserKnownHostsFile <network>_known_hosts

Private networks hostkeys verification[編輯 | 編輯原始碼]

Because different servers on different networks are likely to share a common private IP address, you might want to handle them differently.

本文或本章節的事實準確性存在爭議。

原因: The best solution would not need a warning to use something else in practice.(在 Talk:OpenSSH 中討論)


The best solution is to use the #Network specific configuration to use a different UserKnownHostsFile depending on the network you are on. The second solution, best used as default when you are working on new/prototype networks, would be to simply ignore hostkeys for private networks:

Host 10.* 192.168.*.* 172.31.* 172.30.* 172.2?.* 172.1?.*
    # Disable HostKey verification
    # Trust HostKey automatically
    StrictHostKeyChecking no
    # Do not save the HostKey
    UserKnownHostsFile=/dev/null
    # Do not display: "Warning: Permanently Added ..."
    LogLevel Error

本文或本章節的事實準確性存在爭議。

原因: The known_hosts file records an IP address even when you use hostname to access the server.(在 Talk:OpenSSH 中討論)


警告: In a production environment, make sure to either use the hostname to access the host and/or to use network specific known_hosts files.

在登錄時運行命令[編輯 | 編輯原始碼]

如果你使用的是交互式會話,有多種方法可以在登錄時執行一個命令:

  • 使用遠程主機上的 authorized_keys 文件(見AUTHORIZED_KEYS FILE FORMAT,見sshd(8)
  • 如果伺服器啟用了 ~/.ssh/rc 選項,則使用遠程主機上的 PermitUserRC
  • 使用遠程主機上的 shell 配置文件,例如 .bashrc

轉發代理[編輯 | 編輯原始碼]

SSH代理轉發允許你在連接到一個伺服器時使用你的本地密鑰。建議只對選定的主機啟用代理轉發。

~/.ssh/config
Host myserver.com
    ForwardAgent yes

接下來,配置 SSH代理 並使用 ssh-add 添加你的本地密鑰。

如果你現在連接到一個遠程伺服器,你將能夠使用你的本地密鑰連接到其他服務。

生成新的密鑰對[編輯 | 編輯原始碼]

新的伺服器私鑰可以通過以下方式生成:

  1. 刪除已有的所有密鑰, e.g.:
    # rm /etc/ssh/ssh_host_*_key*
  2. Restarting sshdgenkeys.service 或者以 root 身份運行 ssh-keygen -A.

參見[編輯 | 編輯原始碼]