SSH Public Key Authentication

工作需要对NetCache规则的定期备份。Shell Scripts如下:

################################################################################
# 1) Constents difinations.
################################################################################

# The directory where the backups will be placed.
backups="../backups"

# NetCache server names.
servers="server1 server2 ... servern"

# NetCache domain name.
domain="company.com"

# The objects(rule type) in NetCache need to be backed up.
objects="config.http.acceleration.redirect.rules /
         config.http.acceleration.rules /
         config.https.acceleration.redirect.rules /
         config.https.acceleration.rules"


################################################################################
# 2) Code runs from here
################################################################################

# Check the existance of the backup directory.
if ! [ -d $backups ]; then
    echo "backup directory: $backups seems not exist."
    exit 1;
fi

# Get the current timestamp, which will be append to the backup file names.
timestamp=`date +%F_%T`

# Backup every object in every NetCache server to a server spicific directory.
for server in $servers; do {
    echo "## backing up rules on $server.$domain"

    # The server spicific backup directory.
    destination=$backups/$server
    # Create the directory if not exist.
    [ -d $destination ] || mkdir $destination;

    for object in $objects; do {
        echo "---> backing up rule: $object"
        command="show $object"
        ssh user@$server.$domain $command > $destination/$object.$timestamp
    }; done
}; done

其核心是通过ssh远程执行输出规则的命令,将结果重定向到本地文件:

ssh user@$server.$domain $command > $destination/$object.$timestamp

在脚本的过程中我发现每次执行这一行的时候,ssh都会要求输入一次密码,这使得脚本无法自动运行,即使手工执行也很烦躁。因为我希望自动化SSH的认证过程。

首先想到的是通过脚本输入密码,可是一直找不到正确的方法,在网上找到一个类似的脚本,不过是用Python实现的。

后来通过进一步研究SSH发现,无法使用脚本输入密码是SSH为了安全而有意为之的;Public Key认证才是我所需要的。

Public Key认证是基于非对称加密原理的认证方式,使用Public Key加密的数据只有通过对应的Private Key才能进行解密。

为使用SSH的Public Key认证方式,首先需要通过ssh-keygen创建Key Pair:

$ ssh-keygen

上述命令会在~/.ssh目录下创建名为id_rsa和id_rsa.pub的两个文件,这就是所谓的Key Pair了,其中id_rsa是Private Key,id_rsa.pub是Public Key.

接下来需要将Public Key放到所需登录的服务器上,OpenSSH提供了ssh-copy-id用来完成这一过程,可是因为NetCache的特殊性,这一工具无法使用,因而只有手工完成这一步骤,方法是将Public Key的内容手工复制到远程Home目录下的~/.ssh/authorized_keys文件中。可是把NetCache的命令折腾了半天也没有找到直接编辑文件的命令,准备放弃的时候却以为发现他的web界面里居然实现了这样功能。

完成Public Key的上传之后,再次运行上面的脚本,还是提示输入密码,不过这次输入的是Private Key的密码。这说明上面的配置已经成功了,SSH正在使用Public Key方式进行认证。如果我们在创建Key Pair的时候没有输入密码,这一过程就不会出现。

虽然没有密码保护的Private Key可以实现认证过程的自动化,但是安全性会大打折扣,推荐的做法是使用key-agent 和 key-add, 有兴趣的自己看文档吧。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值