合并 Expect 脚本和 Bash 脚本

合并 Expect 脚本和 Bash 脚本

这是我期望登录远程服务器的脚本,我要求用户输入密码。

#!/usr/bin/expect -f
#Grabbing Password to be used in script further
stty -echo
send_user -- "Enter the Password: "
expect_user -re "(.*)\n"
send_user "\n"
stty echo
set pass $expect_out(1,string)

#Loggin into the Gateway as Normal user
#spawn ssh HOSTNAME@$ip
spawn -noecho ssh -o StrictHostKeyChecking=No HOSTNAME@$ip
expect "HOSTNAME@IP's password:"
send "$pass\n"

#Loggin in as root user
send "$ROOT\r"
expect -exact "Password:*"
send "$pass\r"

现在,下面是我添加用户的 bash 脚本。

#Script to Add User
chattr -i /etc/passwd

read -p 'Please Enter The Username To Add: ' name
echo "$name" > /tmp/userlist.txt
clear
echo -e "Hello $name\nYour Name Is Added To The List."
userfile=/tmp/userlist.txt
username=$(cat /tmp/userlist.txt | tr 'A-Z' 'a-z')
for user in $username
do
useradd $user -N -s /bin/bash
usermod -aG sudo $user
passwd $user

chattr +i /etc/passwd

现在发生的情况是,我可以从本地机器运行预期脚本来登录到远程机器并执行诸如检查内存使用情况之类的操作。

但要添加用户,我需要将 Bash 脚本复制到远程机器上,然后运行该脚本。我的问题是如何在 EXPECT 中使用 BASH 脚本,以便我总是使用 EXPECT 登录到远程机器并运行脚本。

答案1

您需要做的只是send重要的 bash 命令。在 expect 中执行查询:

set root_prompt {# $}     ;# adjust as required

send_user "Please Enter The Username To Add: "
gets user

send -- "useradd $user -N -s /bin/bash\r"
expect -re $root_prompt

send -- "usermod -aG sudo $user\r"
expect -re $root_prompt

send -- "passwd $user\r"
expect -- {
    password: {
        send -- "$the_password\r"
        exp_continue
    }
    -re $root_prompt
}

send -- "echo 'AllowUser $user' >> /etc/ssh/ssd_config\r"
expect -re $root_prompt

send -- "exit\r"
expect eor

相关内容