在 CentOS 系统中,SSH(Secure Shell)是一种加密的网络传输协议,用于在不安全的网络上安全地访问和管理远程服务器。以下是一些常用的 SSH 命令及其用法:
1. 连接到远程服务器
ssh username@hostname
username
:远程服务器的用户名。hostname
:远程服务器的主机名或 IP 地址。
例如:
ssh user@example.com
2. 使用特定端口连接
ssh -p port username@hostname
port
:远程服务器的端口号,默认是 22。
例如:
ssh -p 2222 user@example.com
3. 使用密钥认证
ssh -i /path/to/private_key username@hostname
/path/to/private_key
:私钥文件的路径。
例如:
ssh -i ~/.ssh/id_rsa user@example.com
4. 使用 SSH 代理转发
ssh -A username@hostname
-A
:启用代理转发。
例如:
ssh -A user@example.com
5. 使用 SSH X11 转发
ssh -X username@hostname
-X
:启用 X11 转发。
例如:
ssh -X user@example.com
6. 使用 SSH 配置文件
你可以在 ~/.ssh/config
文件中配置常用的 SSH 连接参数,以便更方便地使用。
例如:
Host example.com HostName example.com User user Port 2222 IdentityFile ~/.ssh/id_rsa
然后可以直接使用:
ssh example.com
7. 断开连接
在 SSH 会话中,可以使用以下命令断开连接:
exit
Ctrl + D
8. 查看 SSH 连接信息
ssh -v username@hostname
-v
:启用详细模式,显示详细的调试信息。
例如:
ssh -v user@example.com
9. 使用 SSH 复制文件
你可以使用 scp
命令在本地和远程服务器之间复制文件。
从本地复制到远程
scp /path/to/local/file username@hostname:/path/to/remote/directory
从远程复制到本地
scp username@hostname:/path/to/remote/file /path/to/local/directory
例如:
scp /home/user/file.txt user@example.com:/home/user/backup/
10. 使用 SSH 隧道
你可以使用 SSH 隧道来转发本地端口到远程服务器。
本地端口转发
ssh -L local_port:remote_host:remote_port username@hostname
例如:
ssh -L 8080:localhost:80 user@example.com
远程端口转发
ssh -R remote_port:localhost:local_port username@hostname
例如:
ssh -R 8080:localhost:80 user@example.com
11. 使用 SSH 执行远程命令
你可以在连接时直接执行远程命令。
ssh username@hostname 'command'
例如:
ssh user@example.com 'ls -l'
这些是 CentOS 系统中常用的一些 SSH 命令及其用法。根据具体需求,你可以组合使用这些命令来实现更复杂的操作。