CentOS SSH命令行操作有哪些技巧

在CentOS系统中,SSH(Secure Shell)是一种非常实用的远程登录工具。以下是一些SSH命令行操作的技巧:

1. 基本连接

  • 连接到远程服务器

    ssh username@hostname
    

    其中,username是远程服务器的用户名,hostname可以是IP地址或域名。

  • 指定端口

    ssh -p port username@hostname
    

    默认端口是22,如果使用其他端口,需要指定-p参数。

2. 使用密钥认证

  • 生成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
    

3. 使用SSH代理

  • 启动SSH代理

    eval $(ssh-agent -s)
    
  • 添加私钥到代理

    ssh-add /path/to/private_key
    

4. 使用SSH配置文件

  • 编辑SSH配置文件

    nano ~/.ssh/config
    
  • 配置文件示例

    Host myserver
        HostName hostname
        User username
        Port port
        IdentityFile /path/to/private_key
    
  • 使用别名连接

    ssh myserver
    

5. 使用SSH隧道

  • 本地端口转发

    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
    

6. 使用SSH保持连接

  • 设置KeepAlive
    ServerAliveInterval 60
    
    这会在60秒内没有活动时发送一个保持连接的信号。

7. 使用SSH命令行工具

  • 查看SSH版本

    ssh -V
    
  • 测试SSH连接

    ssh -o BatchMode=yes -o ConnectTimeout=5 username@hostname
    

8. 使用SSH命令行编辑器

  • 使用vi编辑器

    ssh username@hostname 'vi /path/to/file'
    
  • 使用nano编辑器

    ssh username@hostname 'nano /path/to/file'
    

9. 使用SSH命令行执行命令

  • 在远程服务器上执行单个命令

    ssh username@hostname 'command'
    
  • 在远程服务器上执行多个命令

    ssh username@hostname 'command1; command2; command3'
    

10. 使用SSH命令行传输文件

  • 使用SCP传输文件

    scp /local/path/to/file username@hostname:/remote/path/to/file
    
  • 使用SFTP传输文件

    sftp username@hostname
    

这些技巧可以帮助你更高效地使用SSH进行远程操作。根据具体需求选择合适的技巧,可以大大提升工作效率。