[英]How do I set up an SSH key for some user, if I'm root?
If a root user is running a bash script that configure some stuff on machine for a user. 如果root用户正在运行bash脚本,该脚本为该用户配置了计算机上的某些内容。 The script would configure a git repository and an ssh key for password-less github communication, then it would clone the repository.
该脚本将为无密码的github通信配置git存储库和ssh密钥,然后将克隆存储库。 This will only happens once.
这只会发生一次。
I'm new to bash, how would I do this? 我是bash的新手,我该怎么做?
My solution so far (this script is run as root): 到目前为止,我的解决方案(此脚本以root身份运行):
USERNAME="vagrant"
HOMEDIR="/home/$USERNAME"
apt-get update -y
apt-get install git -y
cp id_rsa* $HOMEDIR/.ssh #copying predefined keys
su -c "eval `ssh-agent -s` ssh-add $HOMEDIR/.ssh/id_rsa" $USERNAME
chmod 400 $HOMEDIR/.ssh/id_rsa
cat $HOMEDIR/.ssh/id_rsa.pub > $HOMEDIR/.ssh/known_hosts
This doesn't work because the key is not being added, I get the error: 这不起作用,因为未添加密钥,我得到了错误:
Could not open a connection to your authentication agent.
With a root user that has no login on a remote host, and /root/.ssh
does not exist, I can interactively ssh in with: 对于在远程主机上没有登录且没有
/root/.ssh
的root用户,我可以使用以下方式交互式地ssh输入:
su - $USERNAME -c "ssh $USERNAME@<remotehost>"
It reads USERNAME's ~/.ssh/known_hosts file
(or prompts for verification). 它读取USERNAME的
~/.ssh/known_hosts file
(或提示进行验证)。 If correct keys exist in USERNAME's ~/.ssh
it uses them. 如果USERNAME的
~/.ssh
存在正确的密钥,它将使用它们。 When done, there is still no /root/.ssh
, ie this is completely done as USERNAME, not root. 完成后,仍然没有
/root/.ssh
,即完全以USERNAME的身份完成,而不是以root的身份完成。
Likewise with git cloning: 同样,对于git clone:
su - $USERNAME -c "git clone remoteuser@host:/path/to/repo"
Just be careful of quoting. 请小心报价。 If you want a variable dereferenced at the time you run
su
, use double quotes. 如果要在运行
su
时取消引用变量,请使用双引号。 If you want a variable dereferenced after su
has handed off to the user's shell, use single quotes. 如果要在
su
移交给用户的shell后取消对变量的引用,请使用单引号。 Example: 例:
su - myuser -c "echo $HOME"
/root
su - myuser -c 'echo $HOME'
/home/myuser
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.