首页 > 解决方案 > 如何使用python更改远程服务器上的文件权限

问题描述

我正在使用 python 的库“Paramiko”将文件写入远程服务器。我想在将文件写入远程服务器时设置文件权限。

目前,我首先编写文件,然后尝试使用“chmod()”更改它的权限,如 paramiko 文档页面所示。但是,在执行我的代码后,我看不到文件权限的任何变化。下面是我的代码。

import paramiko

host='myhost'
user='myuser'
pw='mypassword'
localfilepath='mylocalpath'
remotefilepath='myremotepath'

ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=host,username=user,password=pw)
sftp_client=ssh_client.open_sftp()

#writing file to remote server
sftp_client.put(localfilepath,remotefilepath)

#changing file permissions
sftp_client.chmod(remotefilepath, 0o600)

运行上述代码后,我可以成功地将文件写入服务器,但文件权限保持不变。

之前:'-rwxrwxrwx 1 myuser enduser 3928 Jul 30 13:11 test.csv\n'

之后:'-rwxrwxrwx 1 myuser enduser 3928 Jul 30 13:11 test.csv\n'

请指教。谢谢!

标签: pythonsftpparamiko

解决方案


用于故障排除的 sftp 命令行客户端示例:

sftp myuser@myhost(输入密码)
连接到我的主机。
sftp>帮助
可用命令:
再见 退出 sftp
cd path 将远程目录更改为“路径”
chgrp [-h] grp path 将文件'path'的组更改为'grp'
chmod [-h] mode path 将文件'path'的权限更改为'mode'
chown [-h] own path 将文件'path'的所有者更改为'own'
df [-hi] [path] 显示当前目录的统计信息或
                                   包含“路径”的文件系统
    ...

sftp> ls -l 测试文件
-rwxrwxrwx ? 1428 1434 0 Jul 30 17:46 测试文件
sftp> chmod 600 测试文件
在 /home/myuser/testfile 上更改模式
sftp> ls -l 测试文件
-rw------- ? 1428 1434 0 Jul 30 17:46 测试文件
sftp>退出

在我的情况下chmod 600工作。如果仍然得到相同的结果,则问题与 sftp 有关。可能是 uname 或 sftp 配置问题。


推荐阅读