centos

CentOS Python远程连接怎么设置

小樊
32
2025-08-25 00:51:12
栏目: 编程语言

一、准备工作

  1. 安装SSH服务
    确保CentOS已安装并启动SSH服务:

    sudo yum install openssh-server  # 安装SSH服务
    sudo systemctl start sshd        # 启动服务
    sudo systemctl enable sshd       # 开机自启
    

    (若需修改默认端口或禁用密码登录,可编辑/etc/ssh/sshd_config文件)

  2. 配置防火墙
    若使用firewalld,需开放SSH端口(默认22):

    sudo firewall-cmd --permanent --add-service=ssh
    sudo firewall-cmd --reload
    

二、Python远程连接实现

方法1:使用paramiko库(SSH连接)

  1. 安装库

    pip install paramiko
    
  2. 示例代码(执行远程命令)

    import paramiko
    
    # 配置连接参数
    hostname = 'your_server_ip'
    port = 22
    username = 'your_username'
    password = 'your_password'
    
    # 创建SSH客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        # 连接服务器
        client.connect(hostname, port, username, password)
        
        # 执行命令(如获取系统时间)
        stdin, stdout, stderr = client.exec_command('date')
        print(stdout.read().decode('utf-8'))
    finally:
        client.close()
    

    (支持文件传输、端口转发等,参考)

方法2:使用PyCharm远程解释器

  1. 配置远程环境
    • 打开PyCharm → FileSettingsProject:xxxPython Interpreter → 点击+SSH Interpreter
    • 输入服务器IP、用户名、密码及Python路径(如/usr/bin/python3),完成连接后即可远程运行代码。

方法3:使用VS Code远程开发

  1. 安装插件
    安装Remote - SSH插件,连接后可在VS Code中直接编辑远程文件并运行Python代码。

三、安全建议

四、验证连接

运行测试脚本,若能成功执行远程命令(如获取系统时间),则配置成功。
参考来源:

0
看了该问题的人还看了