Execute ssh command with additional terminal command to any remote user not working script

Hello i am having an issue with bash script and this is the code

now=$(cat hosts1.txt | awk '{print $2;}')
while read n ;do
ssh root@$now 'useradd test1; echo -e "test1\ntest1" | passwd test1 &&  echo "test1  ALL=(ALL:ALL) ALL" >> /etc/sudoers'

When i execute only part with cat, it returns me IP address.
But when I put a command, nothing happend, it not returning me to write something, just like it is freeze, i must put ctrl+c to get job quit.

It is reading from stdin, i.e. your terminal, and thus doesn't freeze but waits for your input. On top, there's a done missing for your while loop.

I added but I am forgot to copy. This is whole

#!/bin/bash

now=$(cat hosts1.txt | awk '{print $2;}')
while read n; do

ssh root@$now 'useradd test1; echo -e "test1\ntest1" | passwd test1 &&  echo "test1  ALL=(ALL:ALL) ALL" >> /etc/sudoers'

done

How can i fix this because it is easier to do it like this and do not connect to all commands via ssh.

If we only knew what you're up to. You read something from stdin into a variable n but then don't use that anywhere.
And, I'm afraid having passwd read from a pipe won't work as it is designed for interactive input.

I am up to add a new user and make this user admin within my remote machines.

passwd does not work that way. It will not read passwords from anything but a terminal.

1 Like

So, it sounds like you want something structured more like:

while read junk now junk
do
	ssh root@$now 'useradd test1; echo -e "test1\ntest1" | passwd test1 &&  echo "test1  ALL=(ALL:ALL) ALL" >> /etc/sudoers'
done < hosts1.txt

but, as RudiC has already said, that isn't the way the passwd utility reads passwords (it reads from its controlling terminal; not from standard input). Therefore, you're going to have to find something other than:

echo -e "test1\ntest1" | passwd test1

to set the user's password.

Does useradd on your system have an option to set a password as a side-effect of creating the account? (This is one of the many reasons why you should always tell us what operating system you're using when you start a new thread in this forum.)

I can't help with the password problem but couldn't you set up a sudoers group on your remote systems and then add the user to that group with the useradd command?

Andrew

You should take a look at this thread:

In which I propose using the -p parameter of useradd to create the user and assign the password all in one go