使用Python Paramiko实现文件上传至Windows Server 2022及反向操作指南

记得配置登录文件信息

 

在服务器上运行的powershell文件用于打开防火墙规则和打开ssh连接

# 检查是否存在允许TCP 22端口的防火墙规则
$firewallRuleName = "OpenSSH-Server-In-TCP"
$rule = Get-NetFirewallRule -Name $firewallRuleName -ErrorAction SilentlyContinue

if ($null -eq $rule) {
    Write-Output "未找到允许SSH连接的防火墙规则,正在创建…"
    # 创建一个新的入站规则来允许TCP 22端口的流量
    New-NetFirewallRule -Name $firewallRuleName `
                        -DisplayName 'OpenSSH Server (sshd)' `
                        -Enabled True `
                        -Direction Inbound `
                        -Protocol TCP `
                        -Action Allow `
                        -LocalPort 22
    Write-Output "防火墙规则创建成功。"
} else {
    Write-Output "已存在允许SSH连接的防火墙规则。"
}

# 检查是否已安装 OpenSSH 服务器
$openSshCapability = Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Server*'

if ($null -eq $openSshCapability -or $openSshCapability.State -ne 'Installed') {
    Write-Output "OpenSSH 服务器未安装或状态不正确,正在尝试安装…"
    Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
} else {
    Write-Output "OpenSSH 服务器已安装"
}

# 确保OpenSSH服务正在运行
$service = Get-Service -Name sshd
if ($service.Status -ne 'Running') {
    if ($service.Status -eq 'Stopped') {
        Write-Output "sshd服务未运行,正在启动…"
        Start-Service sshd
        Set-Service -Name sshd -StartupType 'Automatic'
    } else {
        Write-Warning "sshd服务状态异常:$($service.Status)"
    }
} else {
    Write-Output "sshd服务正在运行。"
}

# 输出当前sshd服务状态
Write-Output "当前sshd服务状态:"
Get-Service sshd

Write-Output "配置完成。你现在应该可以通过SSH远程连接。"

对应的python文件

# -*- coding: utf-8 -*-
import paramiko
import os
import subprocess

# ========================
# 配置 SSH 连接信息
# ========================
hostname = ""  # 远程服务器 IP 地址
port = 22
username = ""  # 远程用户名
password = ""  # 登录密码

# ========================
# 本地和远程文件路径
# ========================
remote_base_dir = r"C:\temp\remote_executable_folder"  # 远程目录
remote_exe_name = "hide_test_executable.exe"  # 远程 .exe 文件名
local_download_path = r"F:\downloaded_hide_test_executable.exe"  # 下载到本地的路径

# 创建 SSH 客户端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    # 建立连接
    ssh.connect(hostname=hostname, port=port, username=username, password=password)
    print("[+] SSH 连接已成功建立")

    # 构建远程 exe 路径
    remote_exe_path = os.path.join(remote_base_dir, remote_exe_name)

    # 使用 SFTP 下载文件
    sftp = ssh.open_sftp()

    try:
        sftp.get(remote_exe_path, local_download_path)
        print(f"[+] 文件已从远程服务器下载至: {local_download_path}")
    except Exception as e:
        raise Exception(f"下载文件时出错: {e}")

    # 关闭 SFTP
    sftp.close()

    # ========================
    # 在本地运行下载的 exe 文件
    # ========================
    print("[+] 正在准备在本地运行下载的程序...")

    try:
        result = subprocess.run(local_download_path, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print("[+] 标准输出:")
        print(result.stdout.decode('gbk', errors='ignore'))
        if result.stderr:
            print("[-] 错误输出:")
            print(result.stderr.decode('gbk', errors='ignore'))
        print("[+] 程序执行结束,退出状态码: 0")
    except subprocess.CalledProcessError as e:
        print(f"[-] 程序执行失败,退出状态码: {e.returncode}")
        print("[-] 错误输出:")
        print(e.stderr.decode('gbk', errors='ignore'))

except FileNotFoundError as fnf_error:
    print(f"[!] 文件错误: {fnf_error}")
except paramiko.AuthenticationException:
    print("[-] 认证失败,请检查用户名或密码")
except paramiko.SSHException as e:
    print(f"[-] SSH 连接异常: {e}")
except Exception as e:
    print(f"[-] 发生了一个未预料的错误: {e}")
finally:
    try:
        ssh.close()
        print("[*] SSH 连接已关闭")
    except:
        pass

作者:才不是立达刘宁宇

物联沃分享整理
物联沃-IOTWORD物联网 » 使用Python Paramiko实现文件上传至Windows Server 2022及反向操作指南

发表回复