PKV
PKV

Reputation: 177

How to change file permissions on a remote server using python

I'm writing a file to a remote server using python's library 'Paramiko'. I want to set file permission as I write files to the remote server.

Currently, I'm writing the file first and then trying to change it's permissions using 'chmod()' as shown in the paramiko documentation page. However, I do not see any changes in the file permissions after executing my code. Below is my code.

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)

After running the above code, I'm successfully able to write file to the server, however the file permissions remain the same.

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

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

Please advise. Thank you!

Upvotes: 0

Views: 5947

Answers (1)

Cole Tierney
Cole Tierney

Reputation: 10314

An sftp command line client example for trouble shooting:

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

In my case chmod 600 worked. If you still get the same results, then the problem is related to sftp. Maybe a uname or sftp configuration problem.

Upvotes: 1

Related Questions