Here is a few different ways to quickly perform a specific activity such as file copy, system updates, gather reports etc on hosts, remotely.


Run commands with ssh:

SSH allows you to run multiple commands seperated by a semicolon.
Example, ssh host-name ‘date;hostname;pwd’

However, in case there is a need to use loops or conditional statements, heredoc can be used since it enables us to run multiple commands remotely and to redirect the output on the local machine.

Run commands on remote hosts with heredoc in a shell script:

#!/bin/sh
for i in `cat serverlist`;do
echo $i
ssh -T -o NumberOfPasswordPrompts=1 username@$i >> server_output 2>&1 <<'EOF'
uname -a 
EOF
echo "-----------------------"
done >> server_output

Run commands on remote hosts with PSSH:

(More details on PSSH can be found at pypi.python.org/pypi/pssh/2.3.1)

$ pssh -h serverlist -i -A sudo 'uname -a'

-A
--askpass
Prompt  for  a  password  and pass it to ssh.  The password may be used for either to unlock a key or for password authentication.
The password is transferred in a fairly secure manner (e.g., it will not show up in argument lists).  However,  be  aware  that  a root user on your system could potentially intercept the password.
-i
--inline
Display standard output and standard error as each host completes.

NOTE: on some servers if you’re running with sudo, it may return a ‘require TTY’ message (an enforcement that can be changed on sudoers file on the remote system).

Run commands on remote hosts with ansible:

(More details on Ansible can be found at (docs.ansible.com)

$ ansible -i serverlist all -s -k -K -m shell -a "uname -a"

-i PATH, --inventory=PATH
The PATH to the inventory, which defaults to /etc/ansible/hosts. Alternatively you can use a comma separated list of hosts or single host with trailing comma host,.

-S, --su
Run operations with su (deprecated, use become).

-s, --sudo
Run the command as the user given by -u and sudo to root (deprecated, use become).

-b, --become
Use privilege escalation (specific one depends on become_method), this does not imply prompting for passwords.

-K, --ask-become-pass
Ask for privilege escalation password.

-k, --ask-pass
Prompt for the connection password, if it is needed for the transport used. For example, using ssh and not having a key-based authentication with ssh-agent.

Run scripts remotely with Ansible:

Create playbook in -> /etc/ansible/playbooks/yourplaybook
A typical playbook would be of the following format:

---
- hosts: "{{hosts}}"
  gather_facts: no

  tasks:
  - name: Run Local script Remotely as ROOT
    script: /path/to/script.sh
    become: true
    become_method: sudo

$ ansible-playbook /path/to/ansible/playbook -i /path/to/serverlist -s -k -K -e hosts=all

This site uses Akismet to reduce spam. Learn how your comment data is processed.