[英]Passing arguments from Python to bash doesn't work as expected
我正在編寫一個腳本,它應該創建一個公共 RSA 密鑰並將其推送到authorized_keys
。
這是我在 Python 中使用的 function:
def push_key():
auth_keys_contents = None
with open('/tmp/{}/public.pub'.format(args.username), 'r') as f:
auth_keys_contents = f.read()
print(auth_keys_contents) #just for testing
os.system('ssh -l root server2 -i ~/.ssh/id_rsa "bash -s" < /home/scripts/script.sh {} {}'.format(args.username, auth_keys_contents))
您看到我使用 ssh 行運行的 bash 腳本很簡單。 這是它的簡短版本:
ssh_dir="/home/${1}/.ssh"
auth_keys_file="/home/${1}/.ssh/authorized_keys"
su $1 -c 'bash -s' <<EOL
...
...
...
echo "$2" > $auth_keys_file
EOL
出於某種原因,當它到達這一行時: echo "$2" > $auth_keys_file
output 並不像我預期的那樣:
user@server2 ~/.ssh [54]> cat authorized_keys
ssh-rsa
user@server2 ~/.ssh [55]>
我不明白為什么它只獲取ssh-rsa
而不是完整的公鑰。 我為echo
嘗試了不同的開關,我嘗試printf
但結果是一樣的。
似乎@Thomas 解決了它。 解決它的另一種方法是替換它:
os.system(' ssh -l root server2 -i ~/.ssh/sid_rsa "bash -s" < /home/scripts/script.sh {} {}'.format(args.username, auth_keys_contents))
有了這個:
ssh_cmd = "bash -s {} {}".format(shlex.quote(args.username), shlex.quote(auth_key_contents)) os.system('ssh -l root server2 -i ~/.ssh/sid_rsa {} < /home/scripts/script.sh'.format(shlex.quote(ssh_cmd)))
問題是我有 2 個嵌套的 shell,我也需要引用兩次。
問題是公鑰中的ssh-rsa
后面有一個空格字符,所以當你將它不帶引號地傳遞給 shell 腳本時,它會將不同的空格分隔部分拆分為單獨的參數。
嘗試替換您當前的行
echo "$2" > $auth_keys_file
和
echo "${@:2}" > $auth_keys_file
這並不理想,因為多個連續的空白字符將折疊成一個空格,但我相信在您的具體情況下這不是問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.