如何使用python更改远程服务器上的文件权限

时间:2020-07-30 18:00:05

标签: python sftp paramiko

我正在使用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最终用户3928 Jul 30 13:11 test.csv \ n'

之后:'-rwxrwxrwx 1 myuser最终用户3928年7月30日13:11 test.csv \ n'

请告知。谢谢!

1 个答案:

答案 0 :(得分:1)

用于解决问题的sftp命令行客户端示例:

sftp myuser@myhost (enter password)
Connected to myhost.
sftp> help
Available commands:
bye                                Quit sftp
cd path                            Change remote directory to 'path'
chgrp [-h] grp path                Change group of file 'path' to 'grp'
chmod [-h] mode path               Change permissions of file 'path' to 'mode'
chown [-h] own path                Change owner of file 'path' to 'own'
df [-hi] [path]                    Display statistics for current directory or
                                   filesystem containing 'path'
    ...

sftp> ls -l testfile
-rwxrwxrwx    ? 1428     1434            0 Jul 30 17:46 testfile
sftp> chmod 600 testfile
Changing mode on /home/myuser/testfile
sftp> ls -l testfile
-rw-------    ? 1428     1434            0 Jul 30 17:46 testfile
sftp> exit

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

相关问题