欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > Python Paramiko上传文件到win ser2022服务器和反向

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

2025/5/22 4:07:07 来源:https://blog.csdn.net/weixin_75280654/article/details/148029794  浏览:    关键词: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}")# 关闭 SFTPsftp.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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词