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.

1 Answer 1

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 
3
  • once we add user how can i make an entry in sshdconfig file. i am using below command. echo "AllowUsers ${user}" >> /etc/ssh/sshd_config Commented Jun 10, 2020 at 7:52
  • My first answer was incomplete. Commented Jun 10, 2020 at 15:06
  • chattr -i /etc/passwd how can i remove and add this permission. Commented Aug 5, 2020 at 8:41

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.