-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild_package.py
More file actions
279 lines (244 loc) · 11.2 KB
/
build_package.py
File metadata and controls
279 lines (244 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import subprocess
import sys
import os
import argparse
import shutil
from pathlib import Path
import logging
import logging.handlers
import traceback
def install_pyinstaller():
"""Install PyInstaller if not already installed"""
try:
import PyInstaller
print("PyInstaller is already installed")
except ImportError:
print("Installing PyInstaller...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
print("PyInstaller installed successfully")
def build_executable():
"""Build standalone executable using PyInstaller"""
try:
print("Building standalone executable...")
# Configure logging with file rotation to prevent permission issues
class SafeRotatingFileHandler(logging.handlers.RotatingFileHandler):
def __init__(self, filename, mode='a', maxBytes=1024*1024, backupCount=3, encoding=None, delay=False):
# Ensure the log directory exists and has proper permissions
import time
from pathlib import Path
log_path = Path(filename)
if log_path.parent and not log_path.parent.exists():
try:
log_path.parent.mkdir(parents=True, exist_ok=True)
except Exception as e:
print(f"Warning: Could not create log directory {log_path.parent}: {e}")
# Try to handle permission issues gracefully
try:
super().__init__(filename, mode, maxBytes, backupCount, encoding, delay)
except (PermissionError, OSError) as e:
# If we can't write to the log file, create a unique log file name
try:
unique_filename = f"{log_path.stem}_{int(time.time())}{log_path.suffix}"
unique_path = log_path.parent / unique_filename if log_path.parent else Path(unique_filename)
super().__init__(str(unique_path), mode, maxBytes, backupCount, encoding, delay)
print(f"Warning: Could not write to {filename}, using {unique_path} instead")
except Exception as e2:
print(f"Error creating log file: {e2}")
# Fallback to console only logging
pass
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
SafeRotatingFileHandler('build_package.log', maxBytes=1024*1024, backupCount=3), # 1MB files, keep 3 backups
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Create PyInstaller command
cmd = [
"pyinstaller",
"--onefile", # Single executable file
"--windowed", # No console window (hidden mode)
"--name", "InfraAgent",
"--add-data", "config.json;.", # Include config file
"--add-data", "agentlogo.ico;.", # Include icon file
"--icon", "agentlogo.ico", # Use the agent logo as icon
"--hidden-import", "win32timezone",
"--hidden-import", "win32api",
"--hidden-import", "win32service",
"--hidden-import", "win32serviceutil",
"--hidden-import", "servicemanager",
"--hidden-import", "win32event",
"--hidden-import", "pystray",
"--hidden-import", "PIL",
"--hidden-import", "PIL.Image",
"--hidden-import", "PIL.ImageDraw",
"--hidden-import", "ctypes",
"--hidden-import", "ctypes.wintypes",
"main.py"
]
# Run PyInstaller
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
print("Executable built successfully!")
print("Output location: dist/InfraAgent.exe")
return True
else:
print("Error building executable:")
print(result.stderr)
return False
except Exception as e:
print(f"Error during build process: {e}")
print(f"Traceback: {traceback.format_exc()}")
return False
def create_package():
"""Create a complete package for distribution"""
try:
print("Creating distribution package...")
# Configure logging with file rotation to prevent permission issues
class SafeRotatingFileHandler(logging.handlers.RotatingFileHandler):
def __init__(self, filename, mode='a', maxBytes=1024*1024, backupCount=3, encoding=None, delay=False):
# Ensure the log directory exists and has proper permissions
import time
from pathlib import Path
log_path = Path(filename)
if log_path.parent and not log_path.parent.exists():
try:
log_path.parent.mkdir(parents=True, exist_ok=True)
except Exception as e:
print(f"Warning: Could not create log directory {log_path.parent}: {e}")
# Try to handle permission issues gracefully
try:
super().__init__(filename, mode, maxBytes, backupCount, encoding, delay)
except (PermissionError, OSError) as e:
# If we can't write to the log file, create a unique log file name
try:
unique_filename = f"{log_path.stem}_{int(time.time())}{log_path.suffix}"
unique_path = log_path.parent / unique_filename if log_path.parent else Path(unique_filename)
super().__init__(str(unique_path), mode, maxBytes, backupCount, encoding, delay)
print(f"Warning: Could not write to {filename}, using {unique_path} instead")
except Exception as e2:
print(f"Error creating log file: {e2}")
# Fallback to console only logging
pass
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
SafeRotatingFileHandler('build_package.log', maxBytes=1024*1024, backupCount=3), # 1MB files, keep 3 backups
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Create package directory
package_dir = Path("package")
if package_dir.exists():
try:
print(f"Removing existing package directory: {package_dir}")
shutil.rmtree(package_dir)
print("Existing package directory removed successfully")
except Exception as e:
print(f"Error removing existing package directory: {e}")
print("\nPossible solutions:")
print("1. Close any applications that might be using files in the package folder")
print("2. Run this script as administrator")
print("3. Restart your computer and try again")
print("4. Use the force_delete.ps1 script: powershell -ExecutionPolicy Bypass -File force_delete.ps1")
return False
package_dir.mkdir()
# Copy executable
exe_path = Path("dist/InfraAgent.exe")
if exe_path.exists():
shutil.copy(exe_path, package_dir / "InfraAgent.exe")
else:
print("Error: Executable not found. Please build it first.")
return False
# Copy config file
config_path = Path("config.json")
if config_path.exists():
shutil.copy(config_path, package_dir / "config.json")
# Copy icon file
icon_file = Path("agentlogo.ico")
if icon_file.exists():
shutil.copy(icon_file, package_dir / "agentlogo.ico")
print("Copied agentlogo.ico to package")
else:
print("Warning: agentlogo.ico not found")
# Create run script
run_script = """@echo off
start "" "InfraAgent.exe" --run-continuous
exit
"""
with open(package_dir / "run_agent.bat", "w") as f:
f.write(run_script)
# Create README file
readme_content = """Infrastructure Agent Package
========================
This package contains the standalone Infrastructure Agent executable that can run
without requiring Python or additional libraries to be installed.
Files:
- InfraAgent.exe: The standalone agent executable with custom icon
- config.json: Configuration file (can be modified before installation)
- run_agent.bat: Script to manually run the agent
To run:
1. Double-click run_agent.bat to start the agent with a visible taskbar icon
OR
2. Run InfraAgent.exe directly
The agent will:
- Collect PC information (OS, CPU, RAM, disk, network, etc.)
- Send data to the configured server
- Display an icon in the taskbar
"""
with open(package_dir / "README.txt", "w") as f:
f.write(readme_content)
print(f"Package created successfully in {package_dir}/")
return True
except Exception as e:
print(f"Error creating package: {e}")
print(f"Traceback: {traceback.format_exc()}")
return False
def main():
# Check if we're running in windowed mode (frozen executable without console)
is_windowed = getattr(sys, 'frozen', False) and sys.stdout is None
# Initialize args with default values
import argparse
args = argparse.Namespace(
build=False,
package=False
)
# Only try to parse arguments if we're not in windowed mode
if not is_windowed:
try:
parser = argparse.ArgumentParser(description='Build Infrastructure Agent package')
parser.add_argument('--build', action='store_true', help='Build executable')
parser.add_argument('--package', action='store_true', help='Create distribution package')
# Try to parse arguments only if we have arguments to parse
if len(sys.argv) > 1:
args = parser.parse_args()
except Exception as e:
# Silently ignore argument parsing errors to prevent crashes in windowed mode
print(f"Silently ignoring argument parsing error in build package: {e}")
# If no arguments provided, do both (default behavior)
if not args.build and not args.package:
args.build = True
args.package = True
# Install PyInstaller if needed
install_pyinstaller()
# Build executable if requested
if args.build:
if not build_executable():
print("Failed to build executable")
return False
# Create package if requested
if args.package:
if not create_package():
print("Failed to create package")
return False
print("Build process completed successfully!")
return True
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)