[root@es1 ~]# ansible all --list-hosts
hosts (2):
192.168.0.12
192.168.0.13
[root@es1 ~]#
[root@es1 ~]# cat /etc/ansible/hosts
[webservers]
192.168.0.12 ansible_ssh_user=root ansible_ssh_pass=123456 http_port=123
192.168.0.13 ansible_ssh_user=root ansible_ssh_pass=123456 http_port=123
[root@es1 ~]#
[root@es1 ~]#
[root@es1 ~]# ansible all -m shell -a 'pwd' -u user
192.168.0.12 | CHANGED | rc=0 >>
/root
192.168.0.13 | CHANGED | rc=0 >>
/root
[root@es1 ~]#
[root@es1 ~]#
[root@es1 ~]# cat /etc/ansible/hosts
[webservers]
192.168.0.12
192.168.0.13
[root@es1 ~]#
[root@es1 ~]#
[root@es1 ~]# ansible all -m shell -a 'pwd' -u user -k
SSH password:
192.168.0.13 | CHANGED | rc=0 >>
/home/user
192.168.0.12 | CHANGED | rc=0 >>
/home/user
[root@es1 ~]#
在远端机器给user用户授权sudo权限(添加这行)
[root@es2 ~]# cat /etc/sudoers|egrep -v '^#|^$'|grep user --color
user ALL=(ALL) ALL
[root@es2 ~]#
[root@es2 ~]# su user
[user@es2 root]$
[user@es2 root]$ sudo ls /root
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:
#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.
[sudo] password for user:
anaconda-ks.cfg elasticsearch-7.6.2-x86_64.rpm
[user@es2 root]$
[root@es1 ~]#
[root@es1 ~]# ansible webservers -m shell -a 'ls /root' -u user -k --become --become-user root -K
SSH password:
BECOME password[defaults to SSH password]:
192.168.0.12 | CHANGED | rc=0 >>
anaconda-ks.cfg
elasticsearch-7.6.2-x86_64.rpm
[root@es1 ~]#
-k 输入连接用户user的密码
-K 输入提权root用户的密码