简体   繁体   中英

How to execute local shell script on remote servers?

I have a shell script in my local machine and I have to execute that shell script on remote servers. I have done some steps as follows:

  1. Paired SSH key from local machine and remote server;
  2. ssh user@hostname 'bash - s' < user_add.sh ;

I am getting an error:

standard in must be a tty
: command not found
bash: line 4: useradd: command not found
Usage: /etc/init.d/vsftpd {start|stop|restart|condrestart|status}
Only root can do that.
chmod: cannot access `/102/prsuser\r': Permission denied
mkdir: cannot create directory `/102/prov/\r': Permission denied
bash: line 8: useradd: command not found
Only root can do that.
chmod: cannot access `/102/prov/PROV_LIS_RESP_DIR\r': Permission denied
chown: cannot access `/102/prov/\r': Permission denied
bash: line 12: /etc/vsftpd/chroot_list: Permission denied

Root login is can't be done normally, we can login as root by switching from normal user account by su - command .

So here is my doubt, how to run the script as a root on remote server and what script used to switch root account at the starting point within my script (user_add.sh)?

您可以修改user_add.sh以便它可以对具有root特权的用户执行命令:

su $ROOT_USER -c "command arg1 arg2"

You can use sudo instead of su (and define all the commands you need to use as your user in the sudoers file)

You could also enable the root account. As a side note, the account doesn't necessarily need to be named "root", you can actually create a new user (named whatever) and then edit the passwd file and assign a uid value of 0 to that account.

Well, it's a little bit strange, what you try to achieve, but you can do it:

ssh user@hostname sudo -S < user_add.sh

The commands that are in user_add.sh will be interpreted at hostname and run within sudo . The user user must have correspondent entry in /etc/sudoers at hostname (with NOPASSWD statement).

If you can't add NOPASSWD you need to run the command this way:

(echo PASSWORD; cat user_add.sh) | ssh user@hostname

Instead of PASSWORD you must write password of user at hostname .

If your sudo doesn't add /sbin to PATH automatically, you need to do it manually:

(echo PASSWORD; echo 'PATH=/sbin:/usr/sbin:$PATH'; cat user_add.sh) \
| ssh user@hostname 

And the last thing. I noted that you have \\r symbols in your script (edited on Windows?). Better remove them:

(echo PASSWORD; echo 'PATH=/sbin:/usr/sbin:$PATH'; cat user_add.sh) \
| tr -d '\r' \
| ssh user@hostname 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM