通过python在ftp中更改权限

6 投票
2 回答
6915 浏览
提问于 2025-04-21 03:44

我正在用Python和ftplib把图片上传到我树莓派上的一个文件夹,路径是/var/www。现在一切都运行得很好,但上传的文件权限是600,我需要的是644的权限。

请问有什么好的办法可以做到这一点呢?我在找类似这样的解决方案:

def ftp_store_avatar(name, image):
    ftp = ftp_connect()
    ftp.cwd("/img")
    file = open(image, 'rb')
    ftp.storbinary('STOR ' + name + ".jpg", file)     # send the file

    [command to set permissions to file]

    file.close()
    ftp.close()

2 个回答

5

在这种情况下,我会使用paramiko中的SFTPClient:

http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html

你可以这样连接、打开文件并更改权限:

import paramiko, stat

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(your_hostname,
               username=user,
               password=passwd)

sftp = client.open_sftp()
remote = sftp.file(remote_filename, 'w')
#remote.writes here
# Here, user has all permissions, group has read and execute, other has read
remote.chmod(stat.S_IRWXU | stats.S_IRGRP | stats.S_IXGRP
             | stats.IROTH)

chmod这个方法的用法和os.chmod是一样的。

9

你需要使用sendcmd这个命令。

下面是一个示例程序,它通过ftplib来改变权限:

#!/usr/bin/env python

import sys
import ftplib

filename = sys.argv[1]
ftp = ftplib.FTP('servername', 'username', 'password')
print ftp.sendcmd('SITE CHMOD 644 ' + filename)
ftp.quit()

祝你编程愉快!

撰写回答