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
相关推荐
优雅的落幕14 分钟前
从零开始的抽奖系统创作(2)
java·服务器·前端
从零开始学习人工智能32 分钟前
Nginx 强制 HTTPS:提升网站安全性的关键一步
运维·nginx·https
努力的搬砖人.1 小时前
Docker 镜像打包到本地
运维·docker·容器
Stephen·You1 小时前
(已解决:基于WSL2技术)Windows11家庭中文版(win11家庭版)如何配置和使用Docker Desktop
运维·docker·容器
塑遂2 小时前
Nginx核心功能
运维·nginx
UFIT2 小时前
postgresql日常维护
运维·服务器
爱莉希雅&&&2 小时前
shell脚本之函数详细解释及运用
linux·运维
麟城Lincoln2 小时前
【Linux笔记】防火墙firewall与相关实验(iptables、firewall-cmd、firewalld)
linux·服务器·笔记·iptables·防火墙·firewalld·firewall
冷冷清清中的风风火火2 小时前
linux查看本机服务器的外网IP命令
linux·服务器·tcp/ip
dal118网工任子仪2 小时前
pikachu靶场 暴力破解
运维·服务器