SSH connection multiplexing is an optimization technique that reuses existing SSH connections to establish new sessions, significantly improving connection speed and efficiency.
Connection Multiplexing Principles
SSH connection multiplexing utilizes SSH's ControlMaster feature to keep the master connection active after the first connection is established. Subsequent new connections are established through the master connection, avoiding repeated authentication and key exchange processes.
Workflow
- First Connection: Establish complete SSH connection (authentication, key exchange)
- Keep Connection: Master connection remains active in background
- Reuse Connection: New connections are quickly established through master connection
- Close Connection: Close master connection after all sessions end
Configuration Methods
1. Command Line Configuration
bash# Enable connection multiplexing ssh -o ControlMaster=auto -o ControlPath=~/.ssh/cm-%r@%h:%p -o ControlPersist=600 user@server # Parameter explanation # ControlMaster=auto: Automatically enable master connection # ControlPath: Control socket path # ControlPersist=600: Keep master connection for 600 seconds (10 minutes)
2. Configuration File Configuration (Recommended)
bash# ~/.ssh/config Host * ControlMaster auto ControlPath ~/.ssh/cm-%r@%h:%p ControlPersist 600 # Or for specific hosts Host production HostName prod.example.com User deploy ControlMaster auto ControlPath ~/.ssh/cm-prod-%r@%h:%p ControlPersist 1800
3. Advanced Configuration Options
bashHost * # Connection multiplexing configuration ControlMaster auto ControlPath ~/.ssh/cm-%r@%h:%p ControlPersist 10m # Connection keep-alive configuration ServerAliveInterval 60 ServerAliveCountMax 3 # Performance optimization Compression yes CompressionLevel 6
Performance Benefits
1. Connection Speed Improvement
bash# Test first connection time time ssh user@server "echo 'First connection'" # Test multiplexed connection time time ssh user@server "echo 'Multiplexed connection'" # Multiplexed connections are typically 10-100 times faster
2. Resource Savings
- Reduce network round trips
- Lower CPU usage (reduce encryption/decryption)
- Save memory (share connection state)
- Reduce server load
3. User Experience Improvement
- Instant response, no latency
- Support concurrent operations
- Suitable for frequent connection scenarios
Practical Application Scenarios
Scenario 1: Frequent Command Execution
bash# Frequently execute remote commands in scripts for i in {1..10}; do ssh user@server "echo 'Command $i'" done # With connection multiplexing, only the first connection needs full setup
Scenario 2: Batch File Transfer
bash# Batch transfer files for file in *.txt; do scp $file user@server:/path/to/destination/ done # Connection multiplexing significantly improves transfer efficiency
Scenario 3: Git Operations
bash# Git automatically benefits when using SSH protocol git clone user@server:project.git git pull origin main git push origin main # All operations reuse the same connection
Scenario 4: Parallel Tasks
bash# Execute multiple SSH commands in parallel ssh user@server "command1" & ssh user@server "command2" & ssh user@server "command3" & wait # All commands reuse the same master connection
Management and Maintenance
1. View Active Connections
bash# View control sockets ls -l ~/.ssh/cm-* # Check connection status ssh -O check user@server # Output example # Master running (pid=12345)
2. Manual Connection Control
bash# Close master connection ssh -O exit user@server # Stop accepting new connections ssh -O stop user@server # Resume accepting new connections ssh -O start user@server # View all multiplexed connections ssh -O forward user@server
3. Clean Up Old Connections
bash# Clean up all control sockets rm -f ~/.ssh/cm-* # Or use find command find ~/.ssh -name "cm-*" -mtime +1 -delete
Troubleshooting
1. Connection Multiplexing Failure
bash# Verbose debugging information ssh -vvv user@server # Check control socket permissions ls -l ~/.ssh/cm-* # Ensure directory permissions are correct chmod 700 ~/.ssh
2. Connection Timeout
bash# Increase ControlPersist time ControlPersist 3600 # Or use ServerAliveInterval to keep connection alive ServerAliveInterval 120 ServerAliveCountMax 3
3. Permission Issues
bash# Ensure ~/.ssh directory permissions are correct chmod 700 ~/.ssh chmod 600 ~/.ssh/config # Check control socket permissions ls -l ~/.ssh/cm-*
Best Practices
1. Global Configuration
bash# ~/.ssh/config Host * ControlMaster auto ControlPath ~/.ssh/cm-%r@%h:%p ControlPersist 600
2. Specific Host Configuration
bash# Use longer keep-alive time for frequently connected hosts Host production ControlPersist 1800 # Use shorter keep-alive time for occasionally connected hosts Host temp-server ControlPersist 60
3. Use in Scripts
bash#!/bin/bash # Use connection multiplexing in scripts SERVER="user@server" # First establish connection ssh -f -N -o ControlMaster=yes -o ControlPath=~/.ssh/cm-%r@%h:%p $SERVER # Execute multiple commands ssh -o ControlPath=~/.ssh/cm-%r@%h:%p $SERVER "command1" ssh -o ControlPath=~/.ssh/cm-%r@%h:%p $SERVER "command2" # Close connection ssh -o ControlPath=~/.ssh/cm-%r@%h:%p -O exit $SERVER
4. Monitoring and Logging
bash# Enable verbose logging LogLevel VERBOSE # Monitor connection status watch -n 5 'ls -l ~/.ssh/cm-*'
Performance Comparison
Test Scenario
bash# Test script #!/bin/bash SERVER="user@server" echo "Testing without multiplexing..." for i in {1..10}; do time ssh -o ControlMaster=no $SERVER "echo $i" done echo "Testing with multiplexing..." for i in {1..10}; do time ssh -o ControlMaster=auto -o ControlPath=~/.ssh/cm-%r@%h:%p $SERVER "echo $i" done
Expected Results
- Without Multiplexing: 1-3 seconds per connection
- With Multiplexing: First connection 1-3 seconds, subsequent connections <0.1 seconds
- Performance Improvement: 10-100 times
Considerations
- Security: Control sockets contain sensitive information, ensure directory permissions are correct
- Resource Usage: Keeping connections consumes memory and file descriptors
- Network Changes: Network environment changes may cause connection failure
- Server Limits: Some servers may limit connection count
- Concurrency Limits: Large number of concurrent connections may affect performance
Advanced Techniques
1. Dynamic Configuration
bash# Dynamically adjust based on network conditions if [ "$(ping -c 1 server | grep 'time=' | awk -F'time=' '{print $2}' | awk '{print $1}')" -lt 50 ]; then ControlPersist 1800 else ControlPersist 300 fi
2. Automatic Cleanup
bash# Regularly clean up expired connections # Add to crontab 0 * * * * find ~/.ssh -name "cm-*" -mtime +1 -delete
3. Integration with Tools
bash# Use in Ansible [defaults] ssh_args = -o ControlMaster=auto -o ControlPath=~/.ssh/cm-%%r@%%h:%%p -o ControlPersist=60s
Connection multiplexing is an important SSH performance optimization technique, especially suitable for frequent connection scenarios, significantly improving work efficiency.