1

This is my expect script for login into a remote server.where i ask user to put password.

#!/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"

Now,below is my bash script to add user.

#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

Now what happens is that expect script i can run from my local machine to login into the remote machine and do stuffs like checking the ram usage n all.

But to add user i want to copy the bash script on remote machine and then run the script. MY QUESTION IS HOW CAN I USE BASH SCRIPT IN EXPECT SO THAT ILL ALWAYS USE THE EXPECT TO LOGIN INTO THE REMOTE MACHINE AND RUN SCRIPTS.

GauravG
  • 19
  • 7

1 Answers1

0

All you need to do is send the important bash commands. Do the queries in 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
glenn jackman
  • 4,630
  • 1
  • 17
  • 20