A Windows SMB/Samba client library for Rust, providing easy-to-use APIs for connecting to, disconnecting from, and listing SMB shares.
- Connect to SMB shares using UNC paths
- Disconnect from SMB shares
- List available shares on a server
- Support for authentication (username/password)
- Optional drive letter mapping
- Configurable connection persistence
- Comprehensive error handling
- Enumerate system network connections
- Support for interactive credential input
The library includes several performance optimizations:
- String buffer reuse: In
list_connect_unc()method, a pre-allocated buffer is reused for formatting connection types, avoiding frequent heap allocations - Memory efficiency: Uses
write!macro with buffer reuse instead offormat!in loops to minimize memory allocations
- No panics: Avoids
unwrap()calls in performance-critical paths with safe error handling - Graceful degradation: Formatting failures return default values instead of panicking
- Pre-sized buffers: Network enumeration uses dynamically resizing buffers starting from 16KB
- Zero-copy operations: Uses string slices where possible to avoid unnecessary cloning
These optimizations are particularly important when enumerating large numbers of network connections, where traditional string formatting could cause significant performance overhead.
Add this to your Cargo.toml:
[dependencies]
smbclient-rs = "0.1.0"use smbclient_rs::{SmbShare, Error};
fn main() -> Result<(), Error> {
// Create a connection manager
let smb_share = SmbShare::new(
"192.168.1.100".to_string(),
"myshare".to_string(),
Some("username"),
Some("password"),
Some('Z'), // Map to drive Z:
false, // Don't persist connection
false, // Don't use interactive mode
);
// Connect to the share
smb_share.connect_unc()?;
// List available shares
match smb_share.list_shares() {
Ok(shares) => {
println!("Available shares: {:?}", shares);
}
Err(e) => eprintln!("Failed to list shares: {}", e),
}
// Disconnect
smb_share.disconnect_unc()?;
Ok(())
}let smb_share = SmbShare::new(
"localhost".to_string(),
"IPC$".to_string(),
None::<String>,
None::<String>,
None, // No drive mapping
false,
false,
);use smbclient_rs::SmbShare;
fn list_network_connections() -> Result<(), Box<dyn std::error::Error>> {
let connections = SmbShare::list_connect_unc()?;
println!("Found {} network connections:", connections.len());
for conn in connections {
println!("Local: '{}', Remote: '{}', Type: '{}', Provider: '{}'",
conn.local_name, conn.remote_name, conn.connection_type, conn.provider_name);
}
Ok(())
}use smbclient_rs::{SmbShare, Error};
fn connect_with_error_handling() -> Result<(), Error> {
let smb_share = SmbShare::new(
"invalid-server".to_string(),
"share".to_string(),
None::<String>,
None::<String>,
None,
false,
false,
);
match smb_share.connect_unc() {
Ok(_) => println!("Connection successful!"),
Err(Error::BadNetName) => eprintln!("Network name is invalid or not found"),
Err(Error::AccessDenied) => eprintln!("Access denied"),
Err(Error::LogonFailure) => eprintln!("Logon failure"),
Err(e) => eprintln!("Other error: {}", e),
}
Ok(())
}The main struct for managing SMB connections.
pub fn new(
server: String,
share: String,
username: Option<impl Into<String>>,
password: Option<impl Into<String>>,
driver: Option<char>,
persist: bool,
interactive: bool,
) -> Selfconnect_unc() -> Result<()>- Connects to the SMB share using UNC pathdisconnect_unc() -> Result<()>- Disconnects from the SMB sharelist_shares() -> Result<Vec<String>>- Lists all shares available on the serverlist_connect_unc() -> Result<Vec<NetworkConnection>>- Lists all network connections in the system (static method)
Represents information about a network connection.
pub struct NetworkConnection {
pub local_name: String, // Local device name (e.g., "X:", empty string for UNC connections)
pub remote_name: String, // Remote network resource (e.g., "\\\\192.168.1.100\\IPC$")
pub connection_type: String, // Connection type (e.g., "disk", "print")
pub provider_name: String, // Provider name
}The library uses the thiserror crate for comprehensive error handling. All Windows SMB error codes are mapped to Rust enums for easy pattern matching.
Main error types include:
AccessDenied- Access deniedBadNetName- Network name is invalidLogonFailure- Logon failureInvalidPassword- Invalid passwordNoNetwork- Network is unavailable- And other Windows SMB errors
The package includes a command-line tool for testing SMB connections. The tool performs the following workflow:
- Connect to the specified SMB share
- List all shares on the server
- Display all network connections in the system
- Disconnect from the share
# Basic usage with authentication
cargo run -- <server> <share> <username> <password>
# Example with authentication
cargo run -- 192.168.1.100 myshare user pass
# Anonymous access to local IPC share
cargo run -- localhost IPC$ "" ""
# Show help
cargo run -- --help
# or
cargo run -- -hsmbclient-rs - Windows SMB/Samba client tool
Usage:
smbclient-rs <server> <share> <username> <password>
Arguments:
<server> Server address (e.g., 192.168.1.100 or localhost)
<share> Share resource name (e.g., myshare or IPC$)
<username> Username for authentication (use "" for anonymous)
<password> Password for authentication (use "" for anonymous)
Examples:
smbclient-rs 192.168.1.100 myshare user pass
smbclient-rs localhost IPC$ "" "" (anonymous access)
Options:
-h, --help Show this help message
Tool workflow:
1. Connect to the specified SMB share
2. List all shares on the server
3. Display all network connections in the system
4. Disconnect from the share
You can also build a standalone executable:
# Build in debug mode
cargo build
# Build in release mode
cargo build --release
# The executable will be available at:
# Debug: target/debug/smbclient-rs.exe
# Release: target/release/smbclient-rs.exe# Using the built executable
./target/debug/smbclient-rs.exe --help
./target/debug/smbclient-rs.exe localhost IPC$ "" ""- Windows operating system (uses Windows Networking API)
- Rust 1.70 or later
- Appropriate network permissions
- Administrator privileges may be required for some operations
This library is specifically designed for Windows platform as it uses Windows-specific APIs (windows crate). Compilation on non-Windows platforms will fail.
MIT License - see LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Run the tests with:
cargo testNote: Some tests require a running SMB server (like localhost with IPC$ share enabled).
Current version: 0.1.0
This library is in early development stage, APIs may change. Feedback and contributions are welcome!
- Windows platform only
- Requires appropriate network permissions
- Some operations may require administrator privileges
- Error handling may not cover all edge cases
- windows-rs - Windows API bindings for Rust
- smbprotocol - SMB protocol implementation
For issues or suggestions, please submit a GitHub Issue.