首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >如何使用Python实现服务器远程登录并执行命令

如何使用Python实现服务器远程登录并执行命令

原创
作者头像
空洞的盒子
发布2025-07-21 16:00:59
发布2025-07-21 16:00:59
21100
代码可运行
举报
文章被收录于专栏:JD的专栏JD的专栏
运行总次数:0
代码可运行

环境依赖

依赖

版本

Python

3.8

paramiko

3.5.1

Ubuntu

64bit

技术实现

使用paramiko实现SSH远程主机登录。

步骤

1.安装paramiko

代码语言:python
代码运行次数:0
运行
复制
pip install paramiko

2.脚本开发

①通过ssh.exec_command直接执行cmd

代码语言:python
代码运行次数:0
运行
复制
import paramiko
import datetime
import os

# 配置项
remote_host = "x.x.x.x"
remote_user = "youruser"
remote_password = "yourpassword"
file_path = "/data/test.log"


def check_file_consistency():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(remote_host, username=remote_user, password=remote_password)
        print(f"✅ 连接成功: {remote_host}")
        # 使用md5命令校验文件一致性
        compress_cmd = f"md5sum {file_path}"
        sh.exec_command(compress_cmd)
        output = shell.recv(1024).decode()
        print(f"✅ 输出内容:{output}")
        
    except Exception as e:
        print(f"❌ 出错: {e}")
    finally:
        ssh.close()

# 执行函数
check_file_consistency(file_path)

②使用invoke_shell执行cmd

当我们执行特定命令或脚本,在Ubuntu系统中单独配置了账号和密码,在执行某些特定命令时需要使用sudo权限。在提交命令后需要自动输入密码。我们这里使用的invoke_shell,类似于开启了一个虚拟的shell命令行,来帮模拟我们手动执行命令的操作。

代码语言:python
代码运行次数:0
运行
复制
import paramiko
import datetime
import os

# 配置项
remote_host = "x.x.x.x"
remote_user = "youruser"
remote_password = "yourpassword"
remote_log_dir = "/data/test.log"

def check_file_consistency(file_path):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    file_full_path = get_file_path() + get_file()
    try:
        ssh.connect(remote_host, port=remote_port, username=remote_user, password=remote_password)
        print(f"✅ 登录成功: {remote_host}")
        # 启动交互式 shell
        shell = ssh.invoke_shell()
        time.sleep(2)
        shell.recv(1024)
        # 要执行的命令
        command = f'sudo md5sum {file_path}\n'
        # 发送命令
        shell.send(command)
        # 等待命令执行完成
        time.sleep(3)
        shell.send(remote_password + '\n')
        time.sleep(2)
        # 获取返回值
        output = shell.recv(1024).decode()
        print(f"✅ 输出内容:{output}")
    except paramiko.AuthenticationException as e:
        print("❌ 认证失败:", e)
    except Exception as e:
        print(f"❌ 出错: {e}")
    finally:
        ssh.close()
        
# 执行函数
check_file_consistency(file_path)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 环境依赖
  • 技术实现
  • 步骤
    • 1.安装paramiko
    • 2.脚本开发
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档