2016-09-23 6 views
0

사용자 생성 및 ssh 액세스 구성을 자동화하려고했습니다. 이것은 그 후, 잘 작동bash 스크립트를 통해 호스트에 SSH 키를 추가하는 방법

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 [email protected] "" 
couldn't read file "<ssh .pub key content> ... 

가 나는 또한 시도 : 난 단지 암호 쿼리가 깜박 얻을, 성공없이

cat $ssh_key | ssh [email protected]$ip "cat >> /home/$new_user/.ssh/authorized_keys" 

그럴 수 없어 기대를이 마지막 방법과 연결하십시오.

+0

http://shellcheck.net/을 사용하는 습관을 들일 수 있습니다. 버그가 발생했을 수 있습니다. –

답변

2

큰 문제는 무시하고 질문에 집중하겠습니다. (입니다. 더 큰 문제는 여기 expect을 사용하지 마십시오. 대신 sshpass을 사용하면이 스크립트를 매우 간단하게 만들 수 있습니다.

지금은 작은 따옴표를 닫으면 다른 따옴표를 사용하지 않습니다. 즉, 변수를 공백으로 대체하면 -c 인수가 expect으로 전달되고 끝납니다.

대신이 일을 :

'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:"; 
... 
' 

:

'foo'"$bar"'baz' 

을 ... 그래서 당신 스크립트는 더 모양을 이 모든 것을 피하면서, 무언가를 고려해보십시오. 다음과 같이하십시오.

#!/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