Shell脚本将rpm scp到远程服务器并安装它。需要一个变量来传递远程主机名

问题描述 投票:1回答:2

我正在尝试编写一种菜单脚本,一旦执行它将实现以下功能:

  1. 询问您以什么用户/密码执行脚本。
  2. 询问远程服务器您想将文件保存到。
  3. 询问文件在本地存储的目录。
  4. 询问所有文件将被传送到的目录。
  5. 复制所有文件。

我的第一个障碍是将密码存储为菜单中的变量。我认为sshpass会很好。我想配置一个像这样的菜单:

title="Select example"
prompt="Pick an option:"
options=("A" "B" "C")

echo "$title"
PS3="$prompt "
select opt in "${options[@]}" "Quit"; do 

    case "$REPLY" in

    1 ) echo "You picked $opt which is option $REPLY";;
    2 ) echo "You picked $opt which is option $REPLY";;
    3 ) echo "You picked $opt which is option $REPLY";;

    $(( ${#options[@]}+1 )) ) echo "Goodbye!"; break;;
    *) echo "Invalid option. Try another one.";continue;;

    esac

done

但是菜单会要求您输入用户名,即文件的本地目录,即远程服务器,远程服务器目录,然后运行它构造的scp命令。

类似这样的东西:

password="your password"
username="username"
Ip="<IP>"
sshpass -p "$password" scp /<PATH>/final.txt $username@$Ip:/root/<PATH>

但是对于如何将所有这些放在一起以便菜单收集所需的信息,然后执行收集的输入,以便仅构造一个scp命令来触发,我有些困惑。

任何人都可以提供任何经验来帮助我构建菜单脚本吗?

谢谢!

linux bash shell unix scp
2个回答
1
投票

您不需要菜单,只需依次输入每个输入。

read -p "Username:" username
read -s -p "Password:" password
read -p "Server IP:" ip
read -p "Local directory:" local
read -p "Remote directory" remote
sshpass -p "$password" scp "/$local/final.txt" "$username@$ip:/root/$remote/"

1
投票

如果您仍然需要菜单,就在这里。我对脚本进行了一些修改,使其在一个一个地输入值的同时使其构造\ print scp命令。

#!/bin/bash

title="Select example"
prompt="Pick an option:"
declare -A options # turn options to an associative array
options[1]='change user name'
options[2]='change user password'
options[3]='change remote host address'
options[4]='change path to source files'
options[5]='change destination path on remote server'

PS3="$prompt "
menu () { # wrap all this to a function to restart it after edition of a element
    echo "$title"
    select opt in "${options[@]}" "Quit"; do
        case "$REPLY" in
            1 ) read -p  "${options[1]}: " user;;
            2 ) read -sp "${options[2]}: " pass;; # read password with option -s to disable output
            3 ) read -p  "${options[3]}: " addr;;
            4 ) read -p  "${options[4]}: " from;;
            5 ) read -p  "${options[5]}: " dest;;

            $(( ${#options[@]}+1 )) ) echo "Goodbye!" ; exit;;
            *) echo "Invalid option. Try another one.";;
        esac
        clear # clear screen to remove inputs
        printf "Creating scp command:\n"
        # we don't want to show password, print *** if password set and 'password not set' if not
        [[ $pass ]] && pass2='***' || pass2='[password not set]'
        # text in [] will be printed if var is empty or not set, it's usefull to add default values to vars ${var:-default_value}
        printf "sshpass -p $pass2 scp -r ${from:-[source not set]}/* ${user:-[user not set]}@${addr:-[host not set]}:${dest:-[destination not set]}/\n\n"
        menu
    done
}

clear # clear screen
menu  # and start menu function

[here我有一个具有simmillar(但功能更丰富)的脚本,请看一下。

© www.soinside.com 2019 - 2024. All rights reserved.