簡體   English   中英

如何通過bash腳本向主機添加ssh密鑰

[英]how to add ssh key to host via bash script

我一直在嘗試自動創建用戶和配置ssh訪問。

到目前為止,我創建了一個訪問主機的腳本,並通過Expect創建了新用戶,如下所示:

expect -c '
spawn ssh '$user'@'$ip';
expect "assword: ";
send "'$passwd'\r";
expect "prompt\n";
send "adduser '$new_user'\r";
...
send "mkdir /home/'$new_user'/.ssh\r";
expect "prompt\n";
send "exit\r";
'

這工作正常,之后我需要將.pub密鑰文件添加到主機中的授權密鑰文件中,這是從哪里開始的。

我試過了:

ssh_key='/home/.../key.pub'
content=$(cat $ssh_key)
expect -c '
spawn ssh '$user'@'$ip' "echo '$content' >> /home/'$new_user'/.ssh/authorized_keys;
expect "password:";
...
'

並得到:

missing "
    while executing 
"spawn ssh root@000.00.00.00 ""
couldn't read file "<ssh .pub key content> ...

我也嘗試過:

cat $ssh_key | ssh $user@$ip "cat >> /home/$new_user/.ssh/authorized_keys"

沒有成功,我只會使密碼查詢閃爍,而無法將期望與最后一種方法聯系起來。

我將忽略這里更大的問題,而將重點放在您的問題上。 更大的問題:不要使用expect在這里-如果依靠sshpass相反,您可以極大地簡化這個腳本)。

現在,當您關閉單引號時,您將不會開始任何其他類型的引號。 這意味着當用空格替換變量時,將結束傳遞給expect-c參數。

而不是這樣做:

'foo'$bar'baz'

做這個:

'foo'"$bar"'baz'

...因此您的腳本看起來更像:

ssh_key='/home/.../key.pub'
content=$(<"$ssh_key")
expect -c '
spawn ssh '"$user"'@'"$ip"' "echo '"$content"' >> /home/'"$new_user"'/.ssh/authorized_keys;
expect "password:";
...
'

不過,在完全避免這種情況方面,請考慮以下內容:

#!/bin/bash
#      ^^^^- NOT /bin/sh

content=$(<"$ssh_key") # more efficient alternative to $(cat ...)

# generate shell-quoted versions of your variables
# these are safe to substitute into a script
# ...even if the original content contains evil things like $(rm -rf /*)
printf -v content_q '%q' "$content"
printf -v new_user_q '%q' "$new_user"

# use those shell-quoted versions remotely
sshpass -f"$password_file" ssh "$host" bash -s <<EOF
adduser ${new_user_q}
printf '%s\n' ${content_q} >>/home/${new_user_q}/.ssh/authorized_keys
EOF

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM