Python - 用户名

时间:2015-10-28 08:52:40

标签: python chown

我正在尝试为chown文件夹所有者创建脚本,但我遇到了一些问题。

/home中有很多文件夹。例如:

/home/user1
/home/user2
/home/user_n

并希望根据文件夹名称更改文件夹的所有者。对于文件夹user1,对于user1所有者user2,需要所有者user2,文件夹user_n需要所有者user_n

现在我有:

#!/usr/bin/python

import os

# Show only filders in /home
path = "/home/"
folderu = [f for f in os.listdir(path)
        if os.path.isdir(os.path.join(path, f))]
print folderu

这是我/home中所有文件夹名称的打印。

我正在尝试这个:

#!/usr/bin/python

import os
import pwd
import grp

# Show only filders in /home
path = "/home/"
folderu = [f for f in os.listdir(path)
        if os.path.isdir(os.path.join(path, f))]
print folderu

for somevar in folderu:
        uid = pwd.getpwnam(folderu).pw_uid
        gid = grp.getgrnam(folderu).gr_gid
        os.chown(folderu, uid, gid)

但这无法奏效。

1 个答案:

答案 0 :(得分:1)

它的工作脚本:

#!/usr/bin/python

import os
import pwd
import grp

# Show only filders in /home
path = "/home/"
folderu = [f for f in os.listdir(path)
    if os.path.isdir(os.path.join(path, f))]

for somevar in folderu:
    uid = pwd.getpwnam(somevar).pw_uid
    gid = grp.getgrnam(somevar).gr_gid
    os.chown(somevar, uid, gid)