ssh-key-for-scp-only

StackExchangeserverfault.com/questions/852309/limit-ssh-key-to-scp-only#answer-852310

generate ssh key

generate key pairs: ~/.ssh/scp_only & ~/.ssh/scp_only.pub

1
2
3
ssh-keygen -t rsa -b 4096 -C scp_only -f ~/.ssh/scp_only
...
...

client machine

~/.ssh/config
1
2
3
4
5
Host server_ipv4
Hostname server_ipv4
User username
IdentitiesOnly yes
IdentityFile ~/.ssh/scp_only

And this is a scp script to transfer file: scpscript.sh

server machine

vim $HOME/.ssh/authorized_keys and paste scp_only.pub content as follows:

allow download and upload:

1
command="if [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^scp.? ]]; then $SSH_ORIGINAL_COMMAND ; else echo Access Denied; fi" ssh-rsa AAAAB3N...

服务器使用zsh作为默认SHELL的话以上命令不管用,客户端执行scp上传时会报错: zsh:1: no such file or directory: scp -r -t XXXXXX
可更换为如下命令,参考链接

具体可用的参数可参考man 8 sshdAUTHORIZED_KEYS部分。

1
no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3N...

download only and only to files from a specific directory:

1
command="if [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^scp[[:space:]]-f[[:space:]]/full/path/to/dir/.? ]]; then $SSH_ORIGINAL_COMMAND ; else echo Access Denied; fi" ssh-rsa AAAAB3N...

more restriction to the key:

1
command="if [[ \"$SSH_ORIGINAL_COMMAND\" =~ ^scp[[:space:]]-f[[:space:]]/full/path/to/dir/.? ]]; then $SSH_ORIGINAL_COMMAND ; else echo ERRO Access Denied; fi",no-pty,no-port-forwarding,no-agent-forwarding,no-X11-forwarding ssh-rsa AAAAB3N...