User Management Examples
Creating Users
Different ways to create users with various configuration options.
var linuxUser = require('linux-sys-user');
// Simple user creation
linuxUser.addUser("john_doe", function (err, user) {
if (err) {
console.error('Error creating user:', err);
return;
}
console.log('User created:', user);
});
// Advanced user creation
linuxUser.addUser({
username: "jane_smith",
create_home: true,
shell: "/bin/bash",
home_dir: "/home/users/jane",
expiredate: "2024-12-31",
system: false,
skel: "/etc/skel"
}, function (err, user) {
if (err) {
console.error('Error creating user:', err);
return;
}
console.log('User created with custom settings:', user);
});
var linuxUserPromise = require('linux-sys-user').promise();
// Simple user creation
linuxUserPromise.addUser("john_doe")
.then(user => console.log('User created:', user))
.catch(err => console.error('Error:', err));
// Advanced user creation
linuxUserPromise.addUser({
username: "jane_smith",
create_home: true,
shell: "/bin/bash",
home_dir: "/home/users/jane",
expiredate: "2024-12-31",
system: false
}).then(user => {
console.log('User created with custom settings:', user);
}).catch(err => {
console.error('Error creating user:', err);
});
var linuxUserPromise = require('linux-sys-user').promise();
async function createUsers() {
try {
// Simple user creation
const user1 = await linuxUserPromise.addUser("john_doe");
console.log('User created:', user1);
// Advanced user creation
const user2 = await linuxUserPromise.addUser({
username: "jane_smith",
create_home: true,
shell: "/bin/bash",
home_dir: "/home/users/jane",
expiredate: "2024-12-31",
system: false
});
console.log('User created with custom settings:', user2);
} catch (err) {
console.error('Error creating users:', err);
}
}
createUsers();
Getting User Information
Retrieve user details and group memberships.
// Get all users
linuxUser.getUsers(function (err, users) {
if (err) {
console.error('Error getting users:', err);
return;
}
console.log('All users:', users);
console.log('Total users:', users.length);
});
// Get specific user info
linuxUser.getUserInfo("john_doe", function (err, user) {
if (err) {
console.error('Error getting user info:', err);
return;
}
if (!user) {
console.log('User not found');
return;
}
console.log('User info:', user);
});
// Get user groups
linuxUser.getUserGroups("john_doe", function (err, groups) {
if (err) {
console.error('Error getting user groups:', err);
return;
}
console.log('User groups:', groups);
});
User Lifecycle Management
Complete user lifecycle from creation to removal.
var testUser = "temp_user_" + Date.now();
async function userLifecycle() {
try {
// Create user
const user = await linuxUserPromise.addUser({
username: testUser,
create_home: true,
shell: "/bin/bash"
});
console.log('User created:', user);
// Set password
await linuxUserPromise.setPassword(testUser, "TempPass123!");
console.log('Password set');
// Get user info
const userInfo = await linuxUserPromise.getUserInfo(testUser);
console.log('User info retrieved:', userInfo);
// Get user groups
const groups = await linuxUserPromise.getUserGroups(testUser);
console.log('User groups:', groups);
// Clean up - remove user
await linuxUserPromise.removeUser(testUser);
console.log('User removed');
} catch (err) {
console.error('Error in user lifecycle:', err);
}
}
userLifecycle();
Warning: The removeUser operation is irreversible and will delete the user's home directory and mail spool.
Group Management Examples
Creating and Managing Groups
Create groups and manage group memberships.
// Create a group
linuxUser.addGroup("developers", function (err, group) {
if (err) {
console.error('Error creating group:', err);
return;
}
console.log('Group created:', group);
});
// Add user to group
linuxUser.addUserToGroup("john_doe", "developers", function (err) {
if (err) {
console.error('Error adding user to group:', err);
return;
}
console.log('User added to group');
});
// Get all groups
linuxUser.getGroups(function (err, groups) {
if (err) {
console.error('Error getting groups:', err);
return;
}
console.log('All groups:', groups);
});
// Get specific group info
linuxUser.getGroupInfo("developers", function (err, group) {
if (err) {
console.error('Error getting group info:', err);
return;
}
console.log('Group info:', group);
});
Security Examples
SSH Key Management
Manage SSH keys for secure authentication.
var sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDBqDmHHhV9HHCY0Rvp6by4N1aBsnjreWKIPaO2UHCURzJk8Sa92jXEfNXpQ1H36yJmirCB+q6XRCKq27ah5M86fCKsm+UfbPlD/X81YH+RnnYgGyh7nwk+llvLKdrzFnF7aHG5/WShj5YUzZO9McIPxyrU1GmMnxEynHp4qSsnmKNJZT2KtpGlP/cvOktNjRWO1hAY8mXG9VShSpqLYWU/AbTV4hZZ2Pr/FdRZq59oRcm9ZGfd13ZMJcPlfhTCeslJfWNx2cuMTSLXRN76MtCmWsPKuVNY6Hj/ILL7JQe8DIxu9AAMiUqFadfFHRGO9dzCh8fKi5lpSMsDKqHHysb504p2ogHDzOUpc/remX3exnvDK1245JXYlNtUkXIexVl+u871PDNbOhx4lSa1nGJGiJCJLW7FlL5mEPrvlgeWaxGihi66redtcPWGVuy2dYytYoI8JanpGlEGFkTOIaKSvDH0ratOxRSlP/Eraxs7w3uVaRvF7/iC348CI63l7T8= user@hostname";
// Verify SSH key
linuxUser.verifySSHKey(sshKey, function (err, keyInfo) {
if (err) {
console.error('Invalid SSH key:', err);
return;
}
console.log('SSH key info:', keyInfo);
});
// Add SSH key to user
linuxUser.addSSHtoUser("john_doe", sshKey, function (err, success) {
if (err) {
console.error('Error adding SSH key:', err);
return;
}
console.log('SSH key added successfully');
});
Note: The addSSHtoUser method automatically creates the .ssh directory with proper permissions (700) and sets the authorized_keys file permissions to 600. The key is only appended if it is not already present, so calling it multiple times with the same key will not create duplicates.
Password Management
Secure password handling and management.
// Set user password
linuxUser.setPassword("john_doe", "SecurePassword123!", function (err) {
if (err) {
console.error('Error setting password:', err);
return;
}
console.log('Password set successfully');
});
// Using promises
async function setUserPassword() {
try {
await linuxUserPromise.setPassword("john_doe", "SecurePassword123!");
console.log('Password set successfully');
} catch (err) {
console.error('Error setting password:', err);
}
}
setUserPassword();
Security Note: Always use strong passwords and follow your organization's password policies. Consider using password generators or policy enforcement tools.
Advanced Examples
User Expiration Management
Manage user account and password expiration policies.
// Get user expiration info
linuxUser.getExpiration("john_doe", function (err, data) {
if (err) {
console.error('Error getting expiration:', err);
return;
}
console.log('Expiration data:', data);
});
// Set user expiration
linuxUser.setExpiration("john_doe", {
lastday: '2024-01-01', // Force password change on next login
expiredate: '2024-12-31', // Account expires on this date
inactive: 30, // 30 days after password expiry
minDays: 1, // Minimum days between password changes
maxDays: 90, // Password expires after 90 days
warnDays: 7 // Warn 7 days before expiry
}, function (err) {
if (err) {
console.error('Error setting expiration:', err);
return;
}
console.log('Expiration policy set');
});
// Using promises and async/await
async function manageUserExpiration() {
try {
// Get current expiration
const current = await linuxUserPromise.getExpiration("john_doe");
console.log('Current expiration:', current);
// Set new expiration policy
await linuxUserPromise.setExpiration("john_doe", {
maxDays: 60, // 60-day password policy
warnDays: 5, // Warn 5 days before expiry
inactive: -1 // Remove inactivity policy
});
console.log('Expiration policy updated');
} catch (err) {
console.error('Error managing expiration:', err);
}
}
manageUserExpiration();
Batch User Creation
Create multiple users efficiently with error handling.
async function createBatchUsers() {
const users = [
{ username: "user1", create_home: true, shell: "/bin/bash" },
{ username: "user2", create_home: true, shell: "/bin/bash" },
{ username: "user3", create_home: false, shell: "/usr/sbin/nologin" }
];
const results = [];
for (const userConfig of users) {
try {
const user = await linuxUserPromise.addUser(userConfig);
results.push({ success: true, user: user });
console.log(`User ${userConfig.username} created successfully`);
} catch (err) {
results.push({ success: false, username: userConfig.username, error: err });
console.error(`Error creating user ${userConfig.username}:`, err);
}
}
// Summary
const successful = results.filter(r => r.success);
const failed = results.filter(r => !r.success);
console.log(`Batch complete: ${successful.length} created, ${failed.length} failed`);
return results;
}
createBatchUsers();
System Audit Script
Complete system audit for user management.
async function systemAudit() {
try {
console.log('Starting system audit...');
// Get all users and groups
const [users, groups] = await Promise.all([
linuxUserPromise.getUsers(),
linuxUserPromise.getGroups()
]);
console.log(`\nSystem Overview:`);
console.log(`- Total users: ${users.length}`);
console.log(`- Total groups: ${groups.length}`);
// Audit user accounts
console.log('\nUser Account Audit:');
const auditPromises = users.slice(0, 5).map(async (user) => {
try {
const expiration = await linuxUserPromise.getExpiration(user.username);
const groups = await linuxUserPromise.getUserGroups(user.username);
return {
username: user.username,
uid: user.uid,
shell: user.shell,
hasHome: user.homedir !== '/',
groups: groups,
passwordAge: expiration.maxDays,
daysUntilExpiry: expiration.accountExpires ?
Math.ceil((new Date(expiration.accountExpires) - new Date()) / (1000 * 60 * 60 * 24)) :
'Never'
};
} catch (err) {
return { username: user.username, error: err.message };
}
});
const auditResults = await Promise.all(auditPromises);
console.log('\nDetailed User Information:');
auditResults.forEach(result => {
if (result.error) {
console.log(` ${result.username}: Error - ${result.error}`);
} else {
console.log(` ${result.username}:`);
console.log(` UID: ${result.uid}, Shell: ${result.shell}`);
console.log(` Home directory: ${result.hasHome ? 'Yes' : 'No'}`);
console.log(` Groups: [${result.groups.join(', ')}]`);
console.log(` Password expires: ${result.daysUntilExpiry} days`);
}
});
console.log('\nAudit complete!');
} catch (err) {
console.error('Audit failed:', err);
}
}
systemAudit();