在CentOS系統中,SSH(Secure Shell)是一種非常實用的遠程登錄工具。以下是一些SSH命令行操作的技巧:
連接到遠程服務器:
ssh username@hostname
其中,username是遠程服務器的用戶名,hostname可以是IP地址或域名。
指定端口:
ssh -p port username@hostname
默認端口是22,如果使用其他端口,需要指定-p參數。
生成SSH密鑰對:
ssh-keygen -t rsa -b 4096
這會生成一個4096位的RSA密鑰對。
將公鑰復制到遠程服務器:
ssh-copy-id username@hostname
這會將你的公鑰添加到遠程服務器的~/.ssh/authorized_keys文件中。
使用私鑰連接:
ssh -i /path/to/private_key username@hostname
啟動SSH代理:
eval $(ssh-agent -s)
添加私鑰到代理:
ssh-add /path/to/private_key
編輯SSH配置文件:
nano ~/.ssh/config
配置文件示例:
Host myserver
HostName hostname
User username
Port port
IdentityFile /path/to/private_key
使用別名連接:
ssh myserver
本地端口轉發:
ssh -L local_port:remote_host:remote_port username@hostname
遠程端口轉發:
ssh -R remote_port:localhost:local_port username@hostname
動態端口轉發(SOCKS代理):
ssh -D local_port username@hostname
ServerAliveInterval 60
這會在60秒內沒有活動時發送一個保持連接的信號。查看SSH版本:
ssh -V
測試SSH連接:
ssh -o BatchMode=yes -o ConnectTimeout=5 username@hostname
使用vi編輯器:
ssh username@hostname 'vi /path/to/file'
使用nano編輯器:
ssh username@hostname 'nano /path/to/file'
在遠程服務器上執行單個命令:
ssh username@hostname 'command'
在遠程服務器上執行多個命令:
ssh username@hostname 'command1; command2; command3'
使用SCP傳輸文件:
scp /local/path/to/file username@hostname:/remote/path/to/file
使用SFTP傳輸文件:
sftp username@hostname
這些技巧可以幫助你更高效地使用SSH進行遠程操作。根據具體需求選擇合適的技巧,可以大大提升工作效率。