# multipass-copy-id
- 脚本类型: shell
- 脚本名称: multipass-copy-id.sh
- 脚本描述: 添加ssh公钥到multipass虚拟机
- 运行环境: Linux, Mac
#!/bin/bash
# 增加本地ssh key 公钥 到 multipass 虚拟机 authorized_keys
# Usage: multipass-copy-id.sh [vm-name]
# Author: LiDong
# Date: 2022-11-13
# 设置出错退出
set -e
# 检查参数
if [ $# -lt 1 ]; then
echo "Usage: multipass-copy-id.sh [vm-name]"
exit 1
fi
# 设置虚拟机名称
vm_name=$1
# 检查虚拟机是否存在
if ! multipass list | grep -q $vm_name; then
echo "Virtual machine $vm_name does not exist"
exit 1
fi
# 检查本地是否有ssh key
if [ ! -f ~/.ssh/id_rsa.pub ]; then
echo "No ssh key found in ~/.ssh/id_rsa.pub"
exit 1
fi
# 增加本地公钥到虚拟机
multipass exec $vm_name -- bash -c "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >>~/.ssh/authorized_keys" <~/.ssh/id_rsa.pub
# 设置权限
multipass exec $vm_name -- bash -c "chmod 600 ~/.ssh/authorized_keys"
# 提示成功
echo "Successfully added ssh key to $vm_name"