My requirement is to append some line of statement to the end of /etc/ssh/sshd_config file, to create some sftp users. Eg:
. . .
Match User sammyfiles
ForceCommand internal-sftp
PasswordAuthentication yes
ChrootDirectory /var/sftp
PermitTunnel no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
NOTE: Above ". . ." shows the continuation of /etc/ssh/sshd_config file. The content below ". . ." is to be appended by my program. There can be several users in my case. I have taken one for example.
To achieve this, i have created a hello.txt file with content as mentioned below:
_Hello Python3!_
I am using below code to edit the file:
import mmap
with open("hello.txt", "r+") as f:
# memory-map the file, size 0 means whole file
map = mmap.mmap(f.fileno(), 0)
# read content via standard file methods
print(map.readline()) # prints "Hello Python!"
# read content via slice notation
print(map[:5]) # prints "Hello"
# update content using slice notation;
# note that new content must have same size
map[14:] = " world!\n"
# ... and read again using standard file methods
map.seek(0)
print(map.readline()) # prints "Hello world!"
# close the map
map.close()
Expected result after cat hello.txt should be Hello Python3! world!
But i am getting error in both python2 and python3. For python3 code is below:
import mmap
with open("hello.txt", "r+") as f:
# memory-map the file, size 0 means whole file
map = mmap.mmap(f.fileno(), 0)
# read content via standard file methods
print(map.readline()) # prints "Hello Python!"
# read content via slice notation
print(map[:5]) # prints "Hello"
# update content using slice notation;
# note that new content must have same size
map[14:] = " world!\n".encode()
# ... and read again using standard file methods
map.seek(0)
print(map.readline()) # prints "Hello world!"
# close the map
map.close()
The Error is below:
root@debian:/python_code# python2 mmaptest4.py
Hello Python3!
Hello
Traceback (most recent call last):
File "mmaptest4.py", line 14, in <module>
map[6:] = " world!\n"
IndexError: mmap slice assignment is wrong size
References:
1)https://docs.python.org/3/library/mmap.html
2)https://pymotw.com/2/mmap/