
我有以下複雜的方法將 ec2 實例上的 IP 位址注入到命令列中。它有效,但有一些明顯的問題,我正在尋找解決這些問題的好方法:
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
IP=`curl -H "X-aws-ec2-metadata-token: \$TOKEN" -v http://169.254.169.254/latest/meta-data/local-ipv4`
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@$IP-\H\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='$IP${debian_chroot:+($debian_chroot)}\u@$IP-\H:\w\$ '
fi
我的方法有幾個我想解決的問題:
- 當載入或登入 bash 時,它會產生一堆不需要的輸出:
Last login: Thu Dec 17 16:57:37 2020 from 22.123.17.122
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 56 100 56 0 0 11200 0 --:--:-- --:--:-- --:--:-- 11200
* Expire in 0 ms for 6 (transfer 0x560383dabf90)
* Trying 169.254.169.254...
* TCP_NODELAY set
* Expire in 200 ms for 4 (transfer 0x560383dabf90)
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Connected to 169.254.169.254 (169.254.169.254) port 80 (#0)
> GET /latest/meta-data/local-ipv4 HTTP/1.1
> Host: 169.254.169.254
> User-Agent: curl/7.64.0
> Accept: */*
> X-aws-ec2-metadata-token: AQAAAEjtIasdfadfasdf5ksdjkjkkasdfe947xQ==
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Accept-Ranges: bytes
< Content-Length: 12
< Content-Type: text/plain
< Date: Thu, 17 Dec 2020 22:52:25 GMT
< Last-Modified: Tue, 15 Dec 2020 14:11:17 GMT
< X-Aws-Ec2-Metadata-Token-Ttl-Seconds: 21600
< Connection: close
< Server: EC2ws
<
{ [12 bytes data]
100 12 100 12 0 0 2400 0 --:--:-- --:--:-- --:--:-- 2400
* Closing connection 0
- 另一個問題是每次我登入 bash 或重新載入 bash 時都會運行。如果 IP 位址已知,我想找出一種繞過此問題的方法。
答案1
您特別要求在第二個命令列中提供curl 的詳細輸出,這佔了輸出的大部分。你應該刪除-v
.然後,要抑制進度表,請使用-s
(在兩個命令中)。除非出現錯誤,否則不會有任何輸出。
如果您在啟動時運行此命令並將生成的 IP 位址寫入文件,然後只需在 bash 設定檔中讀取該檔案的內容,那就更好了。 (這假設實例運行時 IP 位址不會改變,據我所知,這種情況不會發生。)
考慮這樣的本地啟動腳本:
#!/usr/bin/env bash
TOKEN=`curl -s -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" http://169.254.169.254/latest/api/token`
curl -s -H "X-aws-ec2-metadata-token: \$TOKEN" -o /tmp/local-ipv4 http://169.254.169.254/latest/meta-data/local-ipv4
現在您可以在 bash 設定檔中閱讀它:
IP=$(cat /tmp/local-ipv4)