Bash脚本无法从文件中读取

时间:2017-04-12 01:07:18

标签: bash ssh getopts

目的

此脚本用于将一个公共ssh身份文件复制到文件中列出的许多主机

问题

脚本无法从文件中正确读取IP。我相信这是因为它没有读取文件的行。当我回显它正在读取的行(IP)时,它是空白的。

代码

#!/bin/bash
usage="Usage: $(basename "$0") [-h|-u|-i|-p|-f] -- Copys your identity key to a list of remote hosts
where:
-h Show this help text
-u Username of ssh user
-i Location of identity file (Default: /home/$USER/.ssh/id_rsa.pub)
-p Password (not secure)
-f Location of hosts file (Default: ./inventory)"

# Default location for files
CURR_DIR="$(cd "$(dirname "$0")" && pwd)"
HOSTS_FILE=${CURR_DIR}/inventory
IDENT_FILE=/home/$USER/.ssh/id_rsa.pub

# required_flag=false

while getopts 'hu:i:p:f:' option; do
  case $option in
    # Help
    h) echo "$usage"; exit;;
    # Hosts file
    f) HOSTS_FILE=$OPTARG;;
    # Password
    p) PASSWORD=$OPTARG;;
    # Indentity file
    i) IDENT_FILE=$OPTARG; echo "$IDENT_FILE";;
    # Username
    u) USERNAME=$OPTARG;;
    # Missing args
    :) printf "Option -%s\n requires an argument." "-$OPTARG" >&2; echo "$usage" >&2; exit 1;;
    # Illegal option
    \?) printf "Illegal option: -%s\n" "$OPTARG" >&2; echo "$usage" >&2; exit 1;;
  esac
done

shift "$((OPTIND-1))"
#  Decrements the argument pointer so it points to next argument.
#  $1 now references the first non-option item supplied on the command-line
#+ if one exists.

# if ! $required_flag && [[ -d $1 ]]
# then
#     echo "You must specify a hosts file. -h for more help." >&2
#     exit 1
# fi

while IFS= read -r line;
do
     echo "Current IP: " "$IP"
     echo "Current Username: " "$USERNAME"
     echo "Current Identity: " "$IDENT_FILE"
     echo "Current Hosts: " "$HOSTS_FILE"
     echo "Current Password: " "$PASSWORD"
     sshpass -p "$PASSWORD" ssh-copy-id -i "$IDENT_FILE" "$USERNAME"@"$IP"
done < $HOSTS_FILE

输出

$ ./autocopyid -u user -p password
Current IP:  
Current Username:  user
Current Identity:  /home/user/.ssh/id_rsa.pub
Current Hosts:  /home/user/inventory
Current Password:  password
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/user/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: ERROR: ssh: Could not resolve hostname : Name or service not known

1 个答案:

答案 0 :(得分:1)

您没有将变量line用于任何事情。假设$HOSTS_FILE指向每行包含一个IP地址的文件,现在您的循环中的变量line而不是IP的IP地址。但是由于你在循环体中使用变量名IP,你也应该在read语句中使用它。

所以试试

while IFS= read -r IP

而不是

while IFS= read -r line