本文整理汇总了Python中pyftpdlib.authorizers.DummyAuthorizer.remove_user方法的典型用法代码示例。如果您正苦于以下问题:Python DummyAuthorizer.remove_user方法的具体用法?Python DummyAuthorizer.remove_user怎么用?Python DummyAuthorizer.remove_user使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyftpdlib.authorizers.DummyAuthorizer
的用法示例。
在下文中一共展示了DummyAuthorizer.remove_user方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_common_methods
# 需要导入模块: from pyftpdlib.authorizers import DummyAuthorizer [as 别名]
# 或者: from pyftpdlib.authorizers.DummyAuthorizer import remove_user [as 别名]
def test_common_methods(self):
auth = DummyAuthorizer()
# create user
auth.add_user(USER, PASSWD, HOME)
auth.add_anonymous(HOME)
# check credentials
auth.validate_authentication(USER, PASSWD, None)
self.assertRaises(AuthenticationFailed,
auth.validate_authentication, USER, 'wrongpwd', None)
auth.validate_authentication('anonymous', 'foo', None)
auth.validate_authentication('anonymous', '', None) # empty passwd
# remove them
auth.remove_user(USER)
auth.remove_user('anonymous')
# raise exc if user does not exists
self.assertRaises(KeyError, auth.remove_user, USER)
# raise exc if path does not exist
self.assertRaisesRegex(ValueError,
'no such directory',
auth.add_user, USER, PASSWD, '?:\\')
self.assertRaisesRegex(ValueError,
'no such directory',
auth.add_anonymous, '?:\\')
# raise exc if user already exists
auth.add_user(USER, PASSWD, HOME)
auth.add_anonymous(HOME)
self.assertRaisesRegex(ValueError,
'user %r already exists' % USER,
auth.add_user, USER, PASSWD, HOME)
self.assertRaisesRegex(ValueError,
"user 'anonymous' already exists",
auth.add_anonymous, HOME)
auth.remove_user(USER)
auth.remove_user('anonymous')
# raise on wrong permission
self.assertRaisesRegex(ValueError,
"no such permission",
auth.add_user, USER, PASSWD, HOME, perm='?')
self.assertRaisesRegex(ValueError,
"no such permission",
auth.add_anonymous, HOME, perm='?')
# expect warning on write permissions assigned to anonymous user
for x in "adfmw":
self.assertRaisesRegex(
RuntimeWarning,
"write permissions assigned to anonymous user.",
auth.add_anonymous, HOME, perm=x)
示例2: ConfigurableFTPServer
# 需要导入模块: from pyftpdlib.authorizers import DummyAuthorizer [as 别名]
# 或者: from pyftpdlib.authorizers.DummyAuthorizer import remove_user [as 别名]
class ConfigurableFTPServer(object):
"""
This class provides methods to interact with the pyftpdlib FTP server
at a higher abstraction level.
"""
def __init__(self, banner):
"""
Initializes the server's state
Args:
banner: the banner that will be shown when users log in.
"""
self.__authorizer = DummyAuthorizer()
self.__banner = banner
self.__thread = None
def startListenning(self, networkInterface, port, maxConnections, maxConnectionsPerIP, ftpCallback = None,
downloadBandwidthRatio=0.8, uploadBandwitdhRatio=0.8):
"""
Starts the FTP server
Args:
networkInterface: the network interface that will be used to perform the FTP transfers
port: a listenning port
maxConnections: maximum connection number
maxConnectionsPerIP: maximum connection number per IP address
ftpCallback: the callback that will handle the events. If it's none, almost nothing will be
done to handle them.
downloadBandwidthRatio: maximum download bandwidth fraction
uploadBandwidthRatio: maximum upload bandwidth fraction
Returns:
Nothing
"""
ip_address = get_ip_address(networkInterface)
handler = CygnusCloudFTPHandler
handler.ftpCallback = ftpCallback
handler.authorizer = self.__authorizer
handler.banner = self.__banner
link_bandwidth = ChildProcessManager.runCommandInForeground("/sbin/ethtool eth0 | grep -i Speed | cut -b 9-", Exception)
if ("Mb/s" in link_bandwidth) :
power = 1024 ** 2
else :
power = 1024 ** 3
link_bandwidth = int(sub('[^0-9]', '', link_bandwidth))
dtp_handler = ThrottledDTPHandler
dtp_handler.read_limit = link_bandwidth * downloadBandwidthRatio * power
dtp_handler.write_limit = link_bandwidth * uploadBandwitdhRatio * power
handler.dtp_handler = dtp_handler
address = (ip_address, port)
self.__ftpServer = FTPServer(address, handler)
self.__ftpServer.max_cons = maxConnections
self.__ftpServer.max_cons_per_ip = maxConnectionsPerIP
self.__thread = FTPServerThread(self.__ftpServer)
self.__thread.start()
def addUser(self, username, password, homedir, permissions):
"""
Registers a new user
Args:
username: an username
password: a password
homedir: a home directory
permissions: this string sets the new user's permissions.
Read permissions:
- "e" = change directory (CWD command)
- "l" = list filess (LIST, NLST, STAT, MLSD, MLST, SIZE, MDTM commands)
- "r" = retrieve files from the server (RETR command)
Write permissions:
- "a" = append data to an existing f (APPE command)
- "d" = delete file or directory (DELE, RMD commands)
- "f" = rename file or directory (RNFR, RNTO commands)
- "m" = create directory (MKD command)
- "w" = store a file to the server (STOR, STOU commands)
- "M" = change file mode (SITE CHMOD command)
Returns:
Nothing
"""
self.__authorizer.add_user(username, password, homedir, permissions)
def removeUser(self, username):
"""
Deletes an user
Args:
username: an username
Returns:
Nothing
"""
self.__authorizer.remove_user(username)
def stopListenning(self):
"""
Stops the FTP servers
Args:
None
Returns:
Nothing
"""
if (self.__thread == None) :
raise Exception("The FTP server is not running")
self.__thread.stop()
示例3: FTPtest
# 需要导入模块: from pyftpdlib.authorizers import DummyAuthorizer [as 别名]
# 或者: from pyftpdlib.authorizers.DummyAuthorizer import remove_user [as 别名]
class FTPtest(threading.Thread):
# Start the FTP server in a thread with a dummy authorizer, where we can later on feed users to
def __init__(self):
threading.Thread.__init__(self)
# Instantiate a dummy authorizer for managing 'virtual' users
self.authorizer = DummyAuthorizer()
# Instantiate FTP handler class
self.handler = FTPHandler
self.handler.authorizer = self.authorizer
# Specify a masquerade address and the range of ports to use for
# passive connections. Decomment in case you're behind a NAT.
# handler.masquerade_address = '151.25.42.11'
# handler.passive_ports = range(60000, 65535)
# Instantiate FTP server class and listen on every IP address of the machine on port 2121
# If you use this port, please use the iptables command provided in the installation documentation
# If you configured your system so users can listen on ports below 1024, you can set this to 21 and fotget the command
self.address = ("", 2121)
self.server = FTPServer(self.address, self.handler)
# set a limit for connections
self.server.max_cons = 256
self.server.max_cons_per_ip = 5
# Define a new user having full r/w permissions and a read-only
def addUser(self, username, password):
directory = os.getcwd() + "/testdata"
print "adding user " + username + " and pw " + password
self.authorizer.add_user(username, password, directory, perm="elradfmw")
# Removes an user from the server
def delUser(self, username):
self.authorizer.remove_user(username)
print "deletd user", username
# Get some random directories to create within the server
def getRandomDirs(self):
htdocDirs = ["htdocs", "www", "www-data", "htdoc", "web"]
htdocDir = random.choice(htdocDirs)
dirs = [
"isos",
"wareZ",
"pron",
"files",
"logs",
"conficential",
"misc",
"funny",
"photos",
"gf",
"share",
"saves",
]
dirs.append(htdocDir)
numOfPossibleDirs = len(dirs)
numOfDirs = random.randrange(0, numOfPossibleDirs)
return random.sample(set(dirs), numOfDirs)
# Get some random timestamps between the set start timestamp and now, so the timestamps on the server aren't weird
def getRandomTimestamp(self):
endTimestamp = time.time()
startTimestamp = 1353073006.547738
return startTimestamp + random.random() * (endTimestamp - startTimestamp)
# Copy a random subset of data from the possibledata directory to the FTP server directory - then create some random directorys
def populateFiles(self):
# The path to the bait and safe data
source = os.getcwd() + "/possibledata/"
# The path to the FTP server directory
destination = os.getcwd() + "/testdata/"
# The uid and gid of the current user
currentUser = os.getuid()
currentGroup = os.getegid()
# Whipe the whole directory the server had before and create a new one
shutil.rmtree(destination, ignore_errors=True)
os.mkdir(destination)
filesToCleanUp = os.listdir(destination)
for fileToRemove in filesToCleanUp:
os.remove(destination + fileToRemove)
# Get the random subset of files from the bait and safe data and copy them into the FTP directory
allPossibleFiles = os.listdir(source)
print allPossibleFiles
numOfPossibleFiles = len(allPossibleFiles)
numOfFilesToCopy = random.randrange(1, numOfPossibleFiles)
filesToCopy = random.sample(set(allPossibleFiles), numOfFilesToCopy)
for fileToCopy in filesToCopy:
dstFile = destination + fileToCopy
shutil.copy2(source + fileToCopy, dstFile)
os.chown(dstFile, currentUser, currentGroup)
fileTimestamp = self.getRandomTimestamp()
os.utime(dstFile, (fileTimestamp, fileTimestamp))
#.........这里部分代码省略.........
示例4: FTPServerApp
# 需要导入模块: from pyftpdlib.authorizers import DummyAuthorizer [as 别名]
# 或者: from pyftpdlib.authorizers.DummyAuthorizer import remove_user [as 别名]
#.........这里部分代码省略.........
def create_stderr_frame(self, rw, cl):
self.stderr_frame = ttk.Frame(self, relief=constants.SOLID, borderwidth=1)
self.stderr_frame.grid(row=rw, column=cl)
self.old_stderr = sys.stderr
self.err = tkinter.Text(self, width=64, height=12, wrap='none')
self.err.grid(row=rw+1, column=cl, pady=4, padx=5)
sys.stderr = StdoutRedirector(self.err)
def initialise(self):
# Initial values
self.username = tkinter.StringVar()
self.username.set("user")
self.password = tkinter.StringVar()
self.password.set("passwd")
self.listen_ip = tkinter.StringVar()
self.listen_ip.set(self.local_ip_addr)
self.listen_port = tkinter.StringVar()
self.listen_port.set(self.local_port)
self.root_dir['Local'] = tkinter.StringVar()
self.root_dir['Local'].set(os.getcwd() + os.sep)
self.current_state = tkinter.StringVar()
self.current_state.set("NOT RUNNING")
self.root_dir['Remote'] = tkinter.StringVar()
self.root_dir['Remote'].set(os.sep)
# This can be set up only once and saved in a database
self.authorizer.add_user(self.username.get(), self.password.get(),
self.root_dir['Local'].get(), 'elradfmw')
def start_server(self):
port_no = 0
msg = "Please type a port number between 1025 and 65533 inclusive."
try:
port_no = int(self.listen_port.get())
if port_no < LOWEST_PORT_NO or port_no > HIGHEST_PORT_NO:
msg += " Port {0} is not valid.".format(port_no)
raise Exception(msg)
except:
mbox.showinfo(message=msg)
return
self.address = (self.listen_ip.get(), port_no)
self.server = ThreadedFTPServer(self.address, self.handler)
self.server.max_cons = 256
self.server.max_cons_per_ip = 5
self.share_dir(self.root_dir_tree['Local'])
self.start_button.state(['disabled'])
self.stop_button.state(['!disabled'])
self.share_button.state(['disabled'])
self.current_state.set("RUNNING")
threading.Thread(target=self.server.serve_forever).start()
def stop_server(self):
self.server.close_all()
self.start_button.state(['!disabled'])
self.stop_button.state(['disabled'])
self.share_button.state(['!disabled'])
self.current_state.set("NOT RUNNING")
def select_dir(self, dir_tree_view):
if isinstance(dir_tree_view, RootTree):
children = dir_tree_view.get_children('')
if children:
dir_tree_view.delete(children)
old_dir_tree_view_root_dir = dir_tree_view.root_directory.get()
dir_tree_view.root_directory.set(filedialog.askdirectory().replace("/" , str(os.sep)))
if not dir_tree_view.root_directory.get():
dir_tree_view.root_directory.set(old_dir_tree_view_root_dir)
def share_dir(self, dir_tree_view):
if isinstance(dir_tree_view, RootTree):
try:
os.chdir(self.root_dir['Local'].get())
dir_tree_view.root_directory = self.root_dir['Local']
# No need to reconnect because this is only for local dir
dir_tree_view.populate_parent()
# Open up the directory for transferring out/receiving in files
# For use with WindowsAuthorizer or UnixAuthorizer:
# For simplicity's sake, update the homedir everytime Share button is pressed
# self.authorizer.override_user(self.username.get(),
# homedir=self.root_dir['Local'].get())
# For now the workaround:
self.authorizer.remove_user(self.username.get())
self.authorizer.add_user(self.username.get(), self.password.get(),
self.root_dir['Local'].get(), 'elradfmw')
except FileNotFoundError:
mbox.showinfo(message="Invalid Directory!")