可連線遠端主機情況下新增私鑰到遠端主機

devilcry13發表於2019-01-22

一句話新增私鑰到遠端主機,適用於可執行遠端主機命令場景:例如,通過http post命令將命令post到遠端主機並執行
在這裡插入圖片描述

ssh_dir='/home/supdev/.ssh';auth_file=${ssh_dir}/authorized_keys;auth_key='ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEArfaZwds4mExtyNGPNao/tzzXrbUGuzwYJYvK0a6uwcbgmRJ7i6fuJC/QeMRMlalP5N6ZAOoMS4U3J54Z1ejm/SNq0n1JXqELL+ipjc2+BlnGITgh5+eKn9r//fai8F4jZtvDz5+0hv1JVQU561XsnacOtAn1J3ZhiuJ+G12gS/9xcPH0x3iR7+EmN182OmXGEuH5D2cPCe2DsGdYLF1Avia8V48SiXaZZx5smtZnGU4hzB7VgteMalYkdI+tQRQKk6h1VMAsYz0DoaAr6j5YFUOLtqF0M+JHQVrzecR89KnI/CjGT/YgMezOXCceJ6p1jTBuDIdJfFfJ0aagFA7t9Q== rsa 2048-040318';if test -d ${ssh_dir};then if test -f ${auth_file}; then echo 'key exists'; echo ${auth_key}>>${auth_file};echo 'add auth key success';else echo 'key not exists';fi;else ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa; echo ${auth_key}>>${auth_file}; chmod 600 ${auth_file}; fi;

拆解後程式碼如下:

#!/usr/bin/env bash

ssh_dir='/home/supdev/.ssh';
auth_file=${ssh_dir}/authorized_keys;
auth_key='ssh-rsa AAAAB4NzaC1yc2EAAAABIwAAAQEArfaZwds4mExtyNGPNao/tzzXrbUGuzwYJYvK0a6uwcbgmRJ7i6fuJC/QeMRMlalP5N6ZAOoMS4U3J54Z1ejm/SNq0n1JXqELL+ipjc2+BlnGITgh5+eKn9r//fai8F4jZtvDz5+0hv1JVQU561XsnacOtAn1J3ZhiuJ+G12gS/9xcPH0x3iR7+EmN182OmXGEuH5D2cPCe2DsGdYLF1Avia8V48SiXaZZx5smtZnGU4hzB7VgteMalYkdI+tQRQKk6h1VMAsYz0DoaAr6j5YFUOLtqF0M+JHQVrzecR89KnI/CjGT/YgMezOXCceJ6p1jTBuDIdJfFfJ0aagFA7t9Q== rsa 2048-040318';

if test -d ${ssh_dir};then
    if test -f ${auth_file};then
        echo 'key exists'; echo ${auth_key}>>${auth_file};
        echo 'add auth key success';
    else
        echo 'key not exists';
    fi;
else
    ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa;
    echo ${auth_key}>>${auth_file};
    chmod 600 ${auth_file};
fi;

{"command":"ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa;ssh_dir='/home/supdev/.ssh';auth_file=${ssh_dir}/authorized_keys;auth_key='ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEArfSZwds4mExtyNGPNao/tzzXrbUGuzwYJYvK0a6uwcbgmRJ7i6fuJC/QeMRMlalP5N6ZAOoMS4U3J54Z1ejm/SNq0n1JXqELL+ipjc2+BlnGITgh5+eKn9r//fai8F4jZtvDz5+0hv1JVQU561XsnacOtAn1J3ZhiuJ+G12gS/9xcPH0x3iR7+EmN182OmXGEuH5D2cPCe2DsGdYLF1Avia8V48SiXaZZx5smtZnGU4hzB7VgteMalYkdI+tQRQKk6h1VMAsYz0DoaAr6j5YFUOLtqF0M+JHQVrzecR89KnI/CjGT/YgMezOXCceJ6p1jTBuDIdJfFfJ0aagFA7t9Q== rsa 2048-040318';mkdir -p ${ssh_dir};echo ${auth_key}>>${auth_file};chmod 600 ${auth_file};ls ${ssh_dir};chown -R supdev:supdev ${ssh_dir}/*;ls -l ${ssh_dir}"}

相關文章