Files
ClaudeProjectManager-main/vps_connection.py
Claude Project Manager 5f32daf3a4 Status LED
2025-07-08 13:13:46 +02:00

425 Zeilen
16 KiB
Python

"""
VPS Connection Module
Handles SSH connection to VPS server
"""
import os
import tempfile
import subprocess
from utils.logger import logger
class VPSConnection:
def __init__(self):
self.server = "91.99.192.14"
self.username = "claude-dev"
self.password = "z0E1Al}q2H?Yqd!O"
logger.info("VPSConnection initialized")
def create_ssh_script(self) -> str:
"""Create a script for SSH connection with automatic password and Claude start"""
import tempfile
import os
logger.info(f"Creating SSH script for VPS connection to {self.server}")
# Create a simple bash script for SSH connection
bash_script = f'''#!/bin/bash
echo "================================================================================"
echo " Claude VPS Server Connection"
echo "================================================================================"
echo ""
echo "Server: {self.server}"
echo "Username: {self.username}"
echo ""
# Try to use sshpass if available
if command -v sshpass >/dev/null 2>&1; then
echo "Connecting to VPS server and starting Claude automatically..."
echo ""
sshpass -p "{self.password}" ssh -o StrictHostKeyChecking=no -t {self.username}@{self.server} "claude || bash"
else
# Try to install sshpass
echo "Installing sshpass for automatic login..."
if command -v apt-get >/dev/null 2>&1; then
sudo apt-get update -qq 2>/dev/null
sudo apt-get install -y sshpass -qq 2>/dev/null
fi
# Check again if sshpass is now available
if command -v sshpass >/dev/null 2>&1; then
echo "sshpass installed successfully!"
echo "Connecting to VPS server and starting Claude automatically..."
echo ""
sshpass -p "{self.password}" ssh -o StrictHostKeyChecking=no -t {self.username}@{self.server} "claude || bash"
else
echo "Manual password entry required."
echo ""
echo "Password: {self.password}"
echo "(Right-click to paste)"
echo ""
echo "After login, type: claude"
echo ""
ssh -o StrictHostKeyChecking=no {self.username}@{self.server}
fi
fi
echo ""
echo "Connection closed."
echo "Press Enter to exit..."
read
'''
# Save bash script with Unix line endings
with tempfile.NamedTemporaryFile(mode='w', suffix='.sh', delete=False, newline='\n') as f:
f.write(bash_script)
bash_path = f.name
# Convert to WSL path
bash_wsl_path = bash_path.replace('\\', '/').replace('C:', '/mnt/c')
script_content = f"""@echo off
cls
REM Convert line endings and launch WSL with the bash script
wsl dos2unix {bash_wsl_path} 2>nul || wsl sed -i 's/\r$//' {bash_wsl_path}
wsl chmod +x {bash_wsl_path}
wsl bash {bash_wsl_path}
REM Clean up temp file
del "{bash_path}" 2>nul
"""
return script_content
def create_readme_content(self) -> str:
"""Generate README content for VPS project"""
from datetime import datetime
content = f"""# Claude VPS Server
*This README was automatically generated by Claude Project Manager*
## Server Information
- **Server IP**: {self.server}
- **Username**: {self.username}
- **Connection**: SSH (Port 22)
## How to Connect
### Using Claude Project Manager
1. Click on the VPS Server tile
2. Terminal will open with connection instructions
3. Enter the password when prompted
4. Type `claude` after successful login
### Manual Connection
```bash
ssh {self.username}@{self.server}
```
## Available Commands
After connecting to the VPS:
- `claude` - Start Claude CLI
- `ls` - List files
- `cd <directory>` - Change directory
- `exit` - Close SSH connection
## Security Notes
- Keep your password secure
- Don't share SSH credentials
- Always logout when finished (`exit` command)
## Features
This VPS server provides:
- Remote access to Claude
- Persistent environment
- Isolated workspace
- Full Linux environment
## Troubleshooting
### Connection Issues
1. Check internet connection
2. Verify server is online
3. Ensure SSH port (22) is not blocked
4. Try manual SSH command
### Authentication Failed
- Verify password is correct
- Check username spelling
- Ensure caps lock is off
---
## Connection Log
- README generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
"""
return content
def generate_vps_readme(self, readme_path: str):
"""Generate and save VPS README"""
logger.info(f"Generating VPS README at: {readme_path}")
content = self.create_readme_content()
# Create directory if needed
os.makedirs(os.path.dirname(readme_path), exist_ok=True)
# Write README
with open(readme_path, 'w', encoding='utf-8') as f:
f.write(content)
return readme_path
def create_admin_panel_script(self) -> str:
"""Create a script for SSH connection to Admin Panel with directory change"""
import tempfile
import os
logger.info("Creating Admin Panel SSH script")
# Create a simple bash script for SSH connection
bash_script = f'''#!/bin/bash
echo "================================================================================"
echo " Claude Admin Panel Connection"
echo "================================================================================"
echo ""
echo "Server: {self.server}"
echo "Username: {self.username}"
echo "Target Directory: /opt/v2-Docker"
echo ""
# Try to use sshpass if available
if command -v sshpass >/dev/null 2>&1; then
echo "Connecting to VPS server and starting Claude in Admin Panel..."
echo ""
sshpass -p "{self.password}" ssh -o StrictHostKeyChecking=no -t {self.username}@{self.server} "cd /opt/v2-Docker && echo 'Changed to /opt/v2-Docker' && claude || bash"
else
# Try to install sshpass
echo "Installing sshpass for automatic login..."
if command -v apt-get >/dev/null 2>&1; then
sudo apt-get update -qq 2>/dev/null
sudo apt-get install -y sshpass -qq 2>/dev/null
fi
# Check again if sshpass is now available
if command -v sshpass >/dev/null 2>&1; then
echo "sshpass installed successfully!"
echo "Connecting to VPS server and starting Claude in Admin Panel..."
echo ""
sshpass -p "{self.password}" ssh -o StrictHostKeyChecking=no -t {self.username}@{self.server} "cd /opt/v2-Docker && echo 'Changed to /opt/v2-Docker' && claude || bash"
else
echo "Manual password entry required."
echo ""
echo "Password: {self.password}"
echo "(Right-click to paste)"
echo ""
echo "After login:"
echo "1. Type: cd /opt/v2-Docker"
echo "2. Type: claude"
echo ""
ssh -o StrictHostKeyChecking=no {self.username}@{self.server}
fi
fi
echo ""
echo "Connection closed."
echo "Press Enter to exit..."
read
'''
# Save bash script with Unix line endings
with tempfile.NamedTemporaryFile(mode='w', suffix='.sh', delete=False, newline='\n') as f:
f.write(bash_script)
bash_path = f.name
# Convert to WSL path
bash_wsl_path = bash_path.replace('\\', '/').replace('C:', '/mnt/c')
script_content = f"""@echo off
cls
REM Convert line endings and launch WSL with the bash script
wsl dos2unix {bash_wsl_path} 2>nul || wsl sed -i 's/\r$//' {bash_wsl_path}
wsl chmod +x {bash_wsl_path}
wsl bash {bash_wsl_path}
REM Clean up temp file
del "{bash_path}" 2>nul
"""
return script_content
def create_vps_docker_script(self) -> str:
"""Create a script for SSH connection to VPS Docker with docker compose commands"""
import tempfile
import os
logger.info("Creating VPS Docker restart script")
# Create a bash script for SSH connection with docker commands
bash_script = f'''#!/bin/bash
echo "================================================================================"
echo " VPS Docker Admin Panel Restart"
echo "================================================================================"
echo ""
echo "Server: {self.server}"
echo "Username: {self.username}"
echo "Target Directory: /opt/v2-Docker/v2"
echo ""
# Try to use sshpass if available
if command -v sshpass >/dev/null 2>&1; then
echo "Connecting to VPS server and restarting Admin Panel..."
echo ""
sshpass -p "{self.password}" ssh -o StrictHostKeyChecking=no -t {self.username}@{self.server} "cd /opt/v2-Docker/v2 && echo -e '\\n[Restarting Admin Panel Docker containers...]\\n' && docker compose down && echo -e '\\n[Building containers with no cache...]\\n' && docker compose build --no-cache && echo -e '\\n[Starting containers in detached mode...]\\n' && docker compose up -d && echo -e '\\n[SUCCESS] Admin Panel restart completed successfully!\\n' || echo -e '\\n[ERROR] Error during restart process!\\n'"
else
# Try to install sshpass
echo "Installing sshpass for automatic login..."
if command -v apt-get >/dev/null 2>&1; then
sudo apt-get update -qq 2>/dev/null
sudo apt-get install -y sshpass -qq 2>/dev/null
fi
# Check again if sshpass is now available
if command -v sshpass >/dev/null 2>&1; then
echo "sshpass installed successfully!"
echo "Connecting to VPS server and restarting Admin Panel..."
echo ""
sshpass -p "{self.password}" ssh -o StrictHostKeyChecking=no -t {self.username}@{self.server} "cd /opt/v2-Docker/v2 && echo -e '\\n[Restarting Admin Panel Docker containers...]\\n' && docker compose down && echo -e '\\n[Building containers with no cache...]\\n' && docker compose build --no-cache && echo -e '\\n[Starting containers in detached mode...]\\n' && docker compose up -d && echo -e '\\n[SUCCESS] Admin Panel restart completed successfully!\\n' || echo -e '\\n[ERROR] Error during restart process!\\n'"
else
echo "Manual password entry required."
echo ""
echo "Password: {self.password}"
echo "(Right-click to paste)"
echo ""
echo "After login, the following commands will be executed:"
echo "1. cd /opt/v2-Docker/v2"
echo "2. docker compose down"
echo "3. docker compose build --no-cache"
echo "4. docker compose up -d"
echo ""
ssh -o StrictHostKeyChecking=no {self.username}@{self.server}
fi
fi
echo ""
echo "Press Enter to close..."
read
'''
# Save bash script with Unix line endings
with tempfile.NamedTemporaryFile(mode='w', suffix='.sh', delete=False, newline='\n') as f:
f.write(bash_script)
bash_path = f.name
# Convert to WSL path
bash_wsl_path = bash_path.replace('\\', '/').replace('C:', '/mnt/c')
script_content = f"""@echo off
cls
REM Convert line endings and launch WSL with the bash script
wsl dos2unix {bash_wsl_path} 2>nul || wsl sed -i 's/\r$//' {bash_wsl_path}
wsl chmod +x {bash_wsl_path}
wsl bash {bash_wsl_path}
REM Clean up temp file
del "{bash_path}" 2>nul
"""
return script_content
def create_activity_server_script(self) -> str:
"""Create a script for SSH connection to Activity Server"""
import tempfile
import os
logger.info("Creating Activity Server connection script")
# Create a robust script with multiple approaches
script_content = f"""@echo off
cls
echo ================================================================================
echo CPM Activity Server Connection
echo ================================================================================
echo.
echo Server: {self.server}
echo Username: {self.username}
echo Target Directory: /home/claude-dev/cpm-activity-server
echo.
REM Check if PowerShell is available and use it for better plink integration
where powershell >nul 2>&1
if %ERRORLEVEL% EQU 0 (
echo Using PowerShell for enhanced connection...
powershell -NoProfile -ExecutionPolicy Bypass -Command "& {{$plinkPath = Get-Command plink -ErrorAction SilentlyContinue; if ($plinkPath) {{ Write-Host 'Connecting via plink...' -ForegroundColor Green; Write-Host ''; $process = Start-Process -FilePath 'plink' -ArgumentList '-ssh', '-l', '{self.username}', '-pw', '{self.password}', '-t', '{self.server}', 'cd /home/claude-dev/cpm-activity-server && echo \"Successfully changed to Activity Server directory\" && echo && bash -l' -PassThru -NoNewWindow -Wait; if ($process.ExitCode -ne 0) {{ Write-Host ''; Write-Host 'Automatic directory change failed. Starting interactive session...' -ForegroundColor Yellow; Write-Host ''; Write-Host 'IMPORTANT: After login, run these commands:' -ForegroundColor Red; Write-Host ' cd /home/claude-dev/cpm-activity-server' -ForegroundColor White; Write-Host ' claude' -ForegroundColor White; Write-Host ''; & plink -ssh -l {self.username} -pw '{self.password}' -t {self.server} }} }} else {{ Write-Host 'Plink not found, trying standard SSH...' -ForegroundColor Yellow; Write-Host 'Password: {self.password}'; Write-Host 'After login, run: cd /home/claude-dev/cpm-activity-server && claude'; & ssh {self.username}@{self.server} }} }}"
goto end
)
REM First, try the plink approach with RemoteCommand
where plink >nul 2>&1
if %ERRORLEVEL% EQU 0 (
echo Using PuTTY plink for connection...
echo.
REM Try plink with direct command execution
echo Attempting automatic directory change...
plink -batch -ssh -l {self.username} -pw "{self.password}" {self.server} "cd /home/claude-dev/cpm-activity-server && exec bash -l"
REM If that didn't work, try interactive mode
if %ERRORLEVEL% NEQ 0 (
echo.
echo Direct command execution failed. Starting interactive session...
echo.
echo ================================================================================
echo IMPORTANT: After login, please run these commands:
echo.
echo cd /home/claude-dev/cpm-activity-server
echo claude
echo.
echo ================================================================================
echo.
plink -ssh -l {self.username} -pw "{self.password}" -t {self.server}
)
goto end
)
REM Check if we have WSL available
where wsl >nul 2>&1
if %ERRORLEVEL% EQU 0 (
echo Using WSL for connection...
echo.
REM Create inline bash command for WSL
wsl bash -c "echo 'Connecting to Activity Server...' && if command -v sshpass >/dev/null 2>&1; then sshpass -p '{self.password}' ssh -o StrictHostKeyChecking=no -t {self.username}@{self.server} 'cd /home/claude-dev/cpm-activity-server && echo \"Successfully changed to Activity Server directory\" && echo && claude || bash -l'; else echo 'Manual password entry required.' && echo 'Password: {self.password}' && echo && echo 'After login, run: cd /home/claude-dev/cpm-activity-server && claude' && echo && ssh -o StrictHostKeyChecking=no {self.username}@{self.server}; fi"
goto end
)
REM Fallback to standard SSH
echo No automated tools found. Using standard SSH...
echo.
echo ================================================================================
echo Connection Instructions:
echo.
echo 1. Enter this password when prompted: {self.password}
echo (You can right-click to paste in most terminals)
echo.
echo 2. After successful login, run these commands:
echo cd /home/claude-dev/cpm-activity-server
echo claude
echo.
echo ================================================================================
echo.
pause
ssh {self.username}@{self.server}
:end
echo.
echo Connection closed.
pause
"""
return script_content
# Test module
if __name__ == "__main__":
vps = VPSConnection()
print("VPS Connection Module")
print(f"Server: {vps.server}")
print(f"Username: {vps.username}")
print("\nSSH Script Preview:")
print(vps.create_ssh_script()[:300] + "...")