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
相关推荐
雪可问春风1 天前
docker环境部署
运维·docker·容器
lwx9148521 天前
Linux-Shell算术运算
linux·运维·服务器
翻斗包菜1 天前
PostgreSQL 日常维护完全指南:从基础操作到高级运维
运维·数据库·postgresql
somi71 天前
ARM-驱动-02-Linux 内核开发环境搭建与编译
linux·运维·arm开发
海的透彻1 天前
nginx启动进程对文件的权限掌控
运维·chrome·nginx
路溪非溪1 天前
Linux驱动开发中的常用接口总结(一)
linux·运维·驱动开发
此刻觐神1 天前
IMX6ULL开发板学习-01(Linux文件目录和目录相关命令)
linux·服务器·学习
航Hang*1 天前
第3章:Linux系统安全管理——第2节:部署代理服务
linux·运维·服务器·开发语言·笔记·系统安全
fengfuyao9851 天前
VC++基于服务器的点对点文件传输实例
服务器·开发语言·c++
favour_you___1 天前
epoll惊群问题与解决
服务器·网络·tcp/ip·epoll