#!/usr/bin/env python1###############################################################################2#3# CoCalc: Collaborative Calculation in the Cloud4#5# Copyright (C) 2016, Sagemath Inc.6#7# This program is free software: you can redistribute it and/or modify8# it under the terms of the GNU General Public License as published by9# the Free Software Foundation, either version 3 of the License, or10# (at your option) any later version.11#12# This program is distributed in the hope that it will be useful,13# but WITHOUT ANY WARRANTY; without even the implied warranty of14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the15# GNU General Public License for more details.16#17# You should have received a copy of the GNU General Public License18# along with this program. If not, see <http://www.gnu.org/licenses/>.19#20###############################################################################21222324"""25Complete delete a given unix user2627You should put the following in visudo:2829salvus ALL=(ALL) NOPASSWD: /usr/local/bin/create_unix_user.py ""30salvus ALL=(ALL) NOPASSWD: /usr/local/bin/delete_unix_user.py *31"""3233from subprocess import Popen, PIPE34import os, sys3536def cmd(args, exit_on_error=True):37print ' '.join(args)38out = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)39e = out.wait()40stdout = out.stdout.read()41stderr = out.stderr.read()42if e:43print "ERROR --", e44sys.stdout.write(stdout)45sys.stderr.write(stderr)46sys.stdout.flush(); sys.stderr.flush()47if exit_on_error:48sys.exit(e)495051def deluser(username):52if len(username) != 8:53sys.stderr.write("Suspicious username '%s' doesn't have length -- refusing to delete!\n"%username)54sys.exit(1)55else:56# We use the deluser unix command.57# deluser [options] [--force] [--remove-home] [--remove-all-files]58home = os.popen("echo ~%s"%username).read().strip()59cmd(['killall', '-9', '-u', username], exit_on_error=False)60cmd(['deluser', '--force', username], exit_on_error=True)61cmd(['rm', '-rf', home], exit_on_error=False)6263if len(sys.argv) != 2:64sys.stderr.write("Usage: sudo %s <username>\n"%sys.argv[0])65sys.stderr.flush()66sys.exit(1)67else:68deluser(sys.argv[1])6970717273