Python Paramiko上传文件到win ser2022服务器和反向

在服务器上运行的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
相关推荐
大树883 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠3 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质3 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
小宇宙Zz3 天前
Maven依赖冲突
java·服务器·maven
Inhand陈工3 天前
基于台达PLC与映翰通IG502的智慧水产养殖精准投喂与远程运维解决方案
运维·人工智能·物联网·阿里云·信息与通信
酣大智3 天前
ARP代理--工作原理
运维·网络·arp·arp代理
shushangyun_3 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
古城小栈3 天前
Unix 与 Linux 异同小叙
linux·服务器·unix
施努卡机器视觉3 天前
SNK施努卡侧滑门锁上滑轮总成自动化装配线,从零件到组件,全流程精密制造方案
运维·自动化·制造
程序猿阿伟3 天前
《Chrome离线扩展安装的底层逻辑与场景落地指南》
服务器·网络·chrome