我正在编写一些可用于创建 Linux 用户帐户的 Web UI 页面。此 Web UI 将用于 CentOS 6(衍生自 RHEL 6)。我发现关于什么是有效 Linux 用户名的信息不一致且不完整。我查看了源代码,检查了一个 Linux shadow-utils 源代码包,但我并没有确保我正在查看的版本实际上与 CentOS 6 中的版本相同。
下面是我目前使用的代码片段,其中包括复制/粘贴 shadow-utils 包版本 4.1.4.3 中的注释,以及我自己的一些注释,以及一个 Java 正则表达式搜索,以遵循我对 shadow- 的理解 -实用程序源。
chkname.c 中引用的“is_valid_name()”检查显然不是 Linux 上 useradd 命令使用的,因为注释(和 C 代码源)不允许名称以数字开头。但是,useradd 确实允许创建像“1234”这样的帐户。
我很感激帮助我从现在的内容调整到更正确的内容,以及有关如何使用一些略有不同的 is_valid_name 函数实现 useradd.c 的信息。
谢谢!艾伦
/**
* Define constants for use in isNameLinuxCompatible(...) method.
*
* The source for the Linux compatible user name rule is is_valid_name(...) a function in the "shadow" package
* for Linux. The source file for that function has a comment as follows:
* User/group names must match [a-z_][a-z0-9_-]*[$]
* That expression is a little loose/sloppy since
* (1) the trailing $ sign is optional, and
* (2) uppercase A-Z is also ok (and case is significant, 'A' != 'a').
*
* We deal with (1) by using the [$]? form where the ? means zero or more characters (aka "greedy").
* We deal with (2) by using the CASE_INSENSITIVE option.
*
* Another way to express this is:
* 1st character: a-z_ required at least one char
* chars other than first and last: a-z0-9_- optional
* last character: $ optional
* Max length is 31. Min length is 1.
*
* NOTE: The initial ^ and final $ below are important since we need the entire string to satisfy the rule,
* from beginning to end.
*
* See http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html for reference info on pattern matching.
*/
private static final String LINUX_USERNAME_REGEX = "^[a-z_][a-z0-9_-]*[$]?$";
private static final Pattern LINUX_USERNAME_PATTERN = Pattern.compile(LINUX_USERNAME_REGEX, Pattern.CASE_INSENSITIVE);
private static final int LINUX_USERNAME_MINLENGTH = 1;
private static final int LINUX_USERNAME_MAXLENGTH = 31;
/**
* See if username is compatible with standard Linux rules for usernames, in terms of length and
* in terms of content.
*
* @param username the name to be checked for validity
* @return true if Linux compatible, else false
*/
public boolean isNameLinuxCompatible (final String username) {
boolean nameOK = false;
if (username != null) {
int len = username.length();
if ((len >= LINUX_USERNAME_MINLENGTH) && (len <= LINUX_USERNAME_MAXLENGTH)) {
Matcher m = LINUX_USERNAME_PATTERN.matcher(username);
nameOK = m.find();
}
}
return (nameOK);
}