首页主机资讯Ubuntu Python远程控制怎么实现

Ubuntu Python远程控制怎么实现

时间2025-12-18 23:04:05发布访客分类主机资讯浏览716
导读:Ubuntu 上用 Python 实现远程控制的常用方案 方案一 SSH 远程执行与文件传输(推荐) 适用场景:无图形界面服务器、自动化运维、批量任务。 核心库:Paramiko(SSH 客户端与 SFTP)。 安装与最小示例: 安装...

Ubuntu 上用 Python 实现远程控制的常用方案


方案一 SSH 远程执行与文件传输(推荐)

  • 适用场景:无图形界面服务器、自动化运维、批量任务。
  • 核心库:Paramiko(SSH 客户端与 SFTP)。
  • 安装与最小示例:
    • 安装:pip install paramiko
    • 命令执行与 SFTP 上传/下载示例:
      import paramiko
      
      # 1) 远程执行命令
      def remote_execute(hostname, username, password, command, port=22):
          ssh = paramiko.SSHClient()
          ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
          try:
              ssh.connect(hostname, port=port, username=username, password=password, timeout=10)
              stdin, stdout, stderr = ssh.exec_command(command)
              out = stdout.read().decode()
              err = stderr.read().decode()
              if err:
                  print("STDERR:", err)
              print("STDOUT:", out)
          finally:
              ssh.close()
      
      # 2) SFTP 上传/下载
      def sftp_transfer(hostname, username, password, local_path, remote_path, action="put", port=22):
          ssh = paramiko.SSHClient()
          ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
          try:
              ssh.connect(hostname, port=port, username=username, password=password, timeout=10)
              sftp = ssh.open_sftp()
              if action == "put":
                  sftp.put(local_path, remote_path)
                  print(f"Uploaded {
      local_path}
           ->
       {
      remote_path}
      ")
              elif action == "get":
                  sftp.get(remote_path, local_path)
                  print(f"Downloaded {
      remote_path}
           ->
       {
      local_path}
          ")
              sftp.close()
          finally:
              ssh.close()
      
      # 使用示例
      remote_execute("192.168.1.100", "ubuntu", "your_password", "ls -l /tmp")
      sftp_transfer("192.168.1.100", "ubuntu", "your_password",
                    "./local.py", "/home/ubuntu/remote.py", action="put")
      
  • 实用提示:
    • 多条命令请用 & & ; 合并为一条字符串传入 exec_command,避免 cd 后无效的问题。
    • 生产环境建议使用密钥登录并禁用密码,配合 pkey=paramiko.RSAKey.from_private_key_file(...) 更安全。

方案二 图形桌面远程控制(VNC 或 RDP)

  • 适用场景:需要操作 Ubuntu 桌面环境(GUI)。
  • 常见做法:
    • xrdp(RDP):Ubuntu 上安装后可用 Windows 远程桌面连接。
      • 安装与启动:
        sudo apt update
        sudo apt install xrdp
        sudo systemctl enable --now xrdp
        sudo ufw allow 3389/tcp   # 如启用防火墙
        
      • 连接:在客户端输入服务器 IP,使用系统账户登录。
    • x11vnc:将当前显示导出为 VNC 服务,适合已有桌面会话。
      • 安装与设密:
        sudo apt install x11vnc
        x11vnc -storepasswd   # 设置 VNC 密码
        
      • 以 systemd 常驻(示例,按实际用户与显示调整):
        sudo tee /etc/systemd/system/x11vnc.service >
            /dev/null <
            <
            'EOF'
        [Unit]
        Description=Start x11vnc at startup
        After=multi-user.target
        
        [Service]
        Type=simple
        ExecStart=/usr/bin/x11vnc -display :0 -auth /home/ubuntu/.Xauthority -forever -loop -noxdamage -repeat -rfbauth /home/ubuntu/.vnc/passwd -rfbport 5900 -shared
        User=ubuntu
        Group=ubuntu
        
        [Install]
        WantedBy=multi-user.target
        EOF
        sudo systemctl daemon-reload
        sudo systemctl enable --now x11vnc
        
      • 连接:VNC 客户端输入 IP:5900
  • 说明:图形方案通常不直接用 Python 控制桌面,而是用 Python 脚本去启动/停止服务下发命令;桌面交互由 VNC/RDP 客户端完成。

方案三 无公网 IP 或复杂网页登录的自动化

  • 适用场景:服务器在内网、需要模拟浏览器登录门户等。
  • 思路与要点:
    • 在服务器侧使用 Selenium + 无头 Chrome(Chromedriver 与 Chrome 版本需匹配)。
    • 示例(无头登录并检测联网):
      import time
      import requests
      from selenium import webdriver
      from selenium.webdriver.chrome.options import Options
      
      def is_connected():
          try:
              requests.get("https://www.baidu.com", timeout=5)
              return True
          except Exception:
              return False
      
      def portal_login(driver_path, url, user, pwd):
          opts = Options()
          opts.add_argument("--headless")
          opts.add_argument("--disable-gpu")
          driver = webdriver.Chrome(executable_path=driver_path, options=opts)
          try:
              driver.get(url)
              time.sleep(3)  # 等待页面加载
              driver.find_element("xpath", "//input[@id='username']").send_keys(user)
              driver.find_element("xpath", "//input[@id='password']").send_keys(pwd)
              driver.find_element("xpath", "//button[@type='submit']").click()
              time.sleep(5)
          finally:
              driver.quit()
      
      # 使用:portal_login("/usr/local/bin/chromedriver", "https://portal.example.com", "user", "pass")
      
  • 提示:无头模式需确保服务器具备必要的图形依赖;若网络门户频繁变更,需维护元素定位器。

补充建议与常见做法

  • 远程开发与调试:使用 VSCode Remote - SSH 插件,在本地编辑/调试远程 Ubuntu 上的代码,省去手工同步与部署。
  • 文件传输与部署:除 Paramiko 的 SFTP 外,常用 scp 将脚本拷入服务器:
    scp script.py ubuntu@192.168.1.100:/home/ubuntu/
    ssh ubuntu@192.168.1.100 "python3 /home/ubuntu/script.py"
    
  • 运行环境与定时任务:在服务器创建 venv 隔离依赖,或用 cron 定时执行:
    # 每小时执行
    0 * * * * /usr/bin/python3 /home/ubuntu/script.py
    
  • 安全建议:
    • 优先使用 SSH 密钥 登录,禁用 root 直连与密码登录。
    • 限制 SSH 端口访问(如仅内网或跳板机可连),并开启防火墙。
    • 对 VNC/RDP 使用强密码或证书,避免暴露到公网。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Ubuntu Python远程控制怎么实现
本文地址: https://pptw.com/jishu/775612.html
如何配置Linux上MongoDB的认证机制 Linux下MongoDB的内存配置有什么讲究

游客 回复需填写必要信息