File size: 6,329 Bytes
55c0c24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Deploy to GNS3 lab via CONSOLE (telnet) - no SSH required!

This version deploys directly via console/telnet,
which works immediately without network configuration.
"""

import sys
import telnetlib
import time
from pathlib import Path

# Console port mapping (from GNS3 API)
DEVICES = [
    {
        'name': 'SW-HQ-Core',
        'console_port': 5046,
        'config': """
enable
configure terminal
hostname SW-HQ-Core
!
vlan 10
 name Data
vlan 20
 name Voice
!
interface GigabitEthernet0/1
 description Uplink
 switchport mode trunk
 no shutdown
!
end
write memory
"""
    },
    {
        'name': 'SW-West',
        'console_port': 5059,
        'config': """
enable
configure terminal
hostname SW-West
!
vlan 10
 name Data
vlan 20
 name Voice
vlan 30
 name Guest
!
interface GigabitEthernet0/1
 description Uplink
 switchport mode trunk
 no shutdown
!
interface GigabitEthernet0/2
 description Access-Port
 switchport mode access
 switchport access vlan 10
 no shutdown
!
end
write memory
"""
    },
    {
        'name': 'SW-East',
        'console_port': 5069,
        'config': """
enable
configure terminal
hostname SW-East
!
vlan 10
 name Data
vlan 20
 name Voice
vlan 40
 name Management
!
interface GigabitEthernet0/1
 description Uplink
 switchport mode trunk
 no shutdown
!
interface GigabitEthernet0/2
 description Access-Port
 switchport mode access
 switchport access vlan 10
 no shutdown
!
interface Vlan40
 description Management
 ip address 10.0.40.1 255.255.255.0
 no shutdown
!
end
write memory
"""
    },
]

def deploy_to_device(device):
    """Deploy config via console"""
    
    print(f"\n{'='*70}")
    print(f"Deploying to {device['name']} (console port {device['console_port']})")
    print(f"{'='*70}\n")
    
    try:
        # Connect via telnet
        tn = telnetlib.Telnet('localhost', device['console_port'], timeout=10)
        
        # Wake up device
        tn.write(b"\r\n\r\n")
        time.sleep(1)
        
        # Send config
        lines = device['config'].strip().split('\n')
        total_lines = len([l for l in lines if l.strip()])
        
        print(f"Sending {total_lines} configuration commands...")
        
        for i, line in enumerate(lines, 1):
            if line.strip():
                # Show progress every 5 lines
                if i % 5 == 0:
                    print(f"  Progress: {i}/{total_lines} commands sent...")
                
                tn.write(line.encode('ascii') + b"\r\n")
                time.sleep(0.2)
        
        # Final newline and wait
        tn.write(b"\r\n")
        time.sleep(2)
        
        # Get response
        output = tn.read_very_eager().decode('ascii', errors='ignore')
        tn.close()
        
        # Check for errors
        if '%' in output or 'Invalid' in output:
            print(f"\n⚠️  Warning: Possible errors in output")
            print("Last 20 lines of output:")
            print('\n'.join(output.split('\n')[-20:]))
        else:
            print(f"✅ Successfully deployed to {device['name']}")
        
        return True
        
    except Exception as e:
        print(f"❌ Error: {e}")
        return False

def verify_deployment(device):
    """Verify config was applied"""
    
    print(f"\nVerifying {device['name']}...")
    
    try:
        tn = telnetlib.Telnet('localhost', device['console_port'], timeout=5)
        
        # Send show commands
        tn.write(b"\r\n")
        time.sleep(0.5)
        tn.write(b"show running-config | include hostname\r\n")
        time.sleep(1)
        tn.write(b"show vlan brief\r\n")
        time.sleep(1)
        
        output = tn.read_very_eager().decode('ascii', errors='ignore')
        tn.close()
        
        if device['name'] in output:
            print(f"  ✓ Hostname configured correctly")
        
        if 'Vlan' in output or 'VLAN' in output:
            print(f"  ✓ VLANs configured")
        
        return True
        
    except Exception as e:
        print(f"  ⚠️  Verification failed: {e}")
        return False

def main():
    """Main entry point"""
    
    print("\n" + "="*70)
    print("GNS3 Lab Deployment - Console Mode (No SSH Required)")
    print("="*70)
    print("\nThis will deploy configurations to:")
    for dev in DEVICES:
        print(f"  - {dev['name']:15s} (console port {dev['console_port']})")
    
    print("\nDeployment method: Direct console/telnet")
    print("Network access: NOT required")
    
    response = input("\nProceed? (yes/no): ")
    if response.lower() != 'yes':
        print("Aborted.")
        return 1
    
    # Deploy to each device
    print("\n" + "="*70)
    print("Starting Deployment")
    print("="*70)
    
    results = {}
    for device in DEVICES:
        success = deploy_to_device(device)
        results[device['name']] = success
        time.sleep(2)
    
    # Verify deployments
    print("\n" + "="*70)
    print("Verifying Deployments")
    print("="*70)
    
    for device in DEVICES:
        verify_deployment(device)
    
    # Summary
    print("\n" + "="*70)
    print("Deployment Summary")
    print("="*70)
    
    success_count = sum(1 for v in results.values() if v)
    print(f"\n✅ Successfully deployed: {success_count}/{len(DEVICES)} devices")
    
    for name, success in results.items():
        status = "✅ SUCCESS" if success else "❌ FAILED"
        print(f"  {name:15s}: {status}")
    
    print("\n" + "="*70)
    print("🎉 Stage 6 Deployment Complete!")
    print("="*70)
    print("\nYou just deployed configurations to REAL GNS3 devices!")
    print("This demonstrates:")
    print("  ✓ Multi-device deployment")
    print("  ✓ Configuration templating")
    print("  ✓ Automated deployment workflow")
    print("  ✓ Verification checks")
    print("\nNext: You can now test SSH-based deployment if you configure")
    print("      network connectivity between host and GNS3 devices.\n")
    
    return 0 if success_count == len(DEVICES) else 1

if __name__ == '__main__':
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print("\n\nAborted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)